我想找到所有带有$ 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
答案 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);