首页 > 解决方案 > 在 PHP 中使用 preg_match 从字符串中提取变量文本

问题描述

所以,我想我已经接近了,但不能完全让它发挥作用。

我正在使用 curl 从另一个站点提取信息,这些信息存储在 $source 中。

我已经剥离了 $source 的 html 标签等,所以它几乎是纯文本。

我想从 $source 中提取一个可变的人名。从输出中,我可以隔离一些唯一的代码,这些代码将始终围绕名称而没有其他内容,但似乎可以提取名称。

如果我回显 $source,它将包含:

div div div section idname div classcontainer header classsection header h3 John Smith h3 h4 classtext center

我希望取出 John Smith 并将其存储为 $name

这就是我所拥有的,但它似乎不起作用。

// Seek out the persons name
$a=preg_match('/div div div section idname div classcontainer header classsection header h3(\w+)h3 h4 classtext center/',$source,$matches);
$Name = $matches[1];

有什么建议么?

标签: phppreg-match

解决方案


如果名称包含名字和姓氏之间有空格,这将输出 John Smith。

您可以在 JS 中尝试正则表达式,然后将模式粘贴到您的 PHP 代码中。

此模式仅查找 h3 分隔符,并以非贪婪的方式提取中间的任何内容。

<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a search for word characters in a string.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "div div div section idname div classcontainer header classsection header h3 John Smith h3 h4 classtext center"; 
    var patt1 = "/div div div section idname div classcontainer header classsection header h3 (.*?) h3 h4 classtext center/";
    var result = str.match(patt1);
    document.getElementById("demo").innerHTML = result[1];
}
</script>

</body>
</html>

推荐阅读