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

regex php find match between 2 strings including wildcard

我想找到所有包含 $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

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

如果你把它改成别的东西,像这样,它会起作用,你会在 $matches[1]:

中得到你的结果
$regex= "@".$string_before."([^#]+)".$string_after."@";

您只需要转义您的模式(即用 \/ 替换所有 /)

$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);