通过模板占位符在字符串中查找字符串
Find string in string by template placeholder
我正在寻找可以在与我的模板匹配的字符串的任何字符串部分中找到的函数。
例如:
$string = "I found this function in 2015/03/01";
$template = "XXXX/XX/XX";
$go_search = find_string_by_template($template,$string);
echo $go_search;
结果:2015/03/01
真的很简单..它可以更复杂..
$string = "I found this function in 2015/03/01";
preg_match("/(\d{4}\/\d{2}\/\d{2})/", $string, $dates);
var_dump($dates);
简单通用的解决方案:
function template_pattern($tpl)
{
$pattern = '';
$l = strlen($tpl);
for($i=0; $i<$l; $i++)
{
$pattern .= 'D' === $tpl[$i] ? '\d' : ('W' === $tpl[$i] ? '\w' : preg_quote($tpl[$i],'/'));
}
return '/(' . $pattern . ')/';
}
使用示例:
D
匹配一位数字字符,W
匹配一个字母数字字符,其余字符使用正则表达式转义
注意 可以使用更多选项来扩充 template_pattern
功能(例如匹配频繁模式,如特定日期格式、文件格式等,但它很好首先)
preg_match(template_pattern("DDDD/DD/DD"), "I found this function in 2015/03/01", $matches);
print_r($matches);
输出:
Array
(
[0] => 2015/03/01
[1] => 2015/03/01
)
如果你想匹配和捕获整个字符串并将模板提取为一个组,你可以做一个变体:
function template_pattern2($tpl)
{
$pattern = '';
$l = strlen($tpl);
for($i=0; $i<$l; $i++)
{
$pattern .= 'D' === $tpl[$i] ? '\d' : ('W' === $tpl[$i] ? '\w' : preg_quote($tpl[$i],'/'));
}
return '/.*?(' . $pattern . ').*?/';
}
preg_match(template_pattern2("DDDD/DD/DD"), "I found this function in 2015/03/01", $matches);
print_r($matches);
输出:
Array
(
[0] => I found this function in 2015/03/01
[1] => 2015/03/01
)
我正在寻找可以在与我的模板匹配的字符串的任何字符串部分中找到的函数。
例如:
$string = "I found this function in 2015/03/01";
$template = "XXXX/XX/XX";
$go_search = find_string_by_template($template,$string);
echo $go_search;
结果:2015/03/01
真的很简单..它可以更复杂..
$string = "I found this function in 2015/03/01";
preg_match("/(\d{4}\/\d{2}\/\d{2})/", $string, $dates);
var_dump($dates);
简单通用的解决方案:
function template_pattern($tpl)
{
$pattern = '';
$l = strlen($tpl);
for($i=0; $i<$l; $i++)
{
$pattern .= 'D' === $tpl[$i] ? '\d' : ('W' === $tpl[$i] ? '\w' : preg_quote($tpl[$i],'/'));
}
return '/(' . $pattern . ')/';
}
使用示例:
D
匹配一位数字字符,W
匹配一个字母数字字符,其余字符使用正则表达式转义
注意 可以使用更多选项来扩充 template_pattern
功能(例如匹配频繁模式,如特定日期格式、文件格式等,但它很好首先)
preg_match(template_pattern("DDDD/DD/DD"), "I found this function in 2015/03/01", $matches);
print_r($matches);
输出:
Array
(
[0] => 2015/03/01
[1] => 2015/03/01
)
如果你想匹配和捕获整个字符串并将模板提取为一个组,你可以做一个变体:
function template_pattern2($tpl)
{
$pattern = '';
$l = strlen($tpl);
for($i=0; $i<$l; $i++)
{
$pattern .= 'D' === $tpl[$i] ? '\d' : ('W' === $tpl[$i] ? '\w' : preg_quote($tpl[$i],'/'));
}
return '/.*?(' . $pattern . ').*?/';
}
preg_match(template_pattern2("DDDD/DD/DD"), "I found this function in 2015/03/01", $matches);
print_r($matches);
输出:
Array
(
[0] => I found this function in 2015/03/01
[1] => 2015/03/01
)