正则表达式php找到2个字符串之间的匹配,包括通配符

时间:2015-01-07 00:06:24

标签: php regex

我想找到所有带有$ string_before [MATCH] anytext $ string_after

的结果

PHP代码:

$page = "anything/pages/Reading/120002/anything><div class='test'>";

$string_before = '/pages/Reading/';
$string_after = '/(.*?)><div class';
$regex= "'/".$string_before."([^#]+)".$string_after."'/";

preg_match_all($regex, $page, $matches); 
var_dump($matches);

// I should be getting "120002"  in the example above

上面的代码不起作用......输出为NULL 有任何想法吗... 感谢

###修改

我现在试过这个:

$page = "anything/pages/Reading/120002/anything><div class='test'>";

$delimiter = "#";
$string_before = '/pages/Reading/';
$string_after = '/(.*?)><div class=';
$regex = $delimiter.$string_before."([^#]+)".$string_after.$delimiter;

echo $regex.'<br>';

preg_match_all($pattern, $page, $matches); 
var_dump($matches);

我的正则表达式是:

#/pages/Reading/([^#]+)/(.*?)> 

因此$ string_after无法正确输出...

我收到以下2个错误:

Notice: Undefined variable: pattern on line 66 (that's the preg_match_all)

Warning: preg_match_all(): Empty regular expression  on line 66
NULL

2 个答案:

答案 0 :(得分:1)

PHP正则表达式在前后采用分隔符。您已将分隔符设置为'/,这将无效,因为1)它是两个字符,2)您在$string_before$string_after变量中使用了多个斜杠。

如果您将其更改为其他内容,就像这样,它会起作用,您会在$matches[1]中获得结果:

$regex= "@".$string_before."([^#]+)".$string_after."@";

答案 1 :(得分:0)

你只需要逃避你的模式(即替换所有/用\ /)

$page = "anything/pages/Reading/120002/anything><div class='test'>";

$string_before = '\/pages\/Reading\/';
$string_after = '\/(.*?)><div class';
$regex= "/".$string_before."([^#]+)".$string_after."/";

preg_match_all($regex, $page, $matches); 
var_dump($matches);