[英]Extract a string that is the difference between two other strings in PHP
[英]Extract multiple Strings between two String in PHP
我正在尝试完成这项工作,但我不能:
$str = "<html>1</html><html>2</html><html>3</html>";
$matches = array();
preg_match_all("(?<=<html>)(.*?)(?=</html>)", $str, $matches);
foreach ($matches as $d)
{
echo $d;
}
我做错了什么? output 必须是:
123
这应该适合你:
$str = "<html>1</html><html>2</html><html>3</html>";
preg_match_all("~(?<=<html>).*?(?=</html>)~", $str, $matches);
foreach ($matches[0] as $d) {
echo $d;
}
Output:
123
变化是:
preg_match_all
function 模式中使用缺少的正则表达式定界符~
foreach
循环中使用$matches[0]
而不是$matches
preg_match_all
之前无需声明/初始化$matches
您需要添加定界符(我用过!
)并且您可以跳过前瞻/后视。 只需围绕您想要的数字创建一个捕获组。 没有其他的。 然后在第二个matches
元素中查找具有各个值的数组。
例子:
preg_match_all("!<html>(.*?)</html>!", $str, $matches);
foreach ($matches[1] as $d)
{
echo $d;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.