php - 在 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];
有什么建议么?
解决方案
如果名称包含名字和姓氏之间有空格,这将输出 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>
推荐阅读
- android - getCurrentUser NullPointerException
- python-3.x - 如何在 Google App Engine 中进行 apt-get install
- go - 拒绝服务资源耗尽请求
- azure - 如何将 Azure 存储帐户活动日志发送到 Azure 日志分析工作区
- python - OpenCV沿曲线检测点
- azure - 在 yaml 管道配置中声明时,不会在 Azure Devops 中自动创建环境
- wordpress - Gutenberg 11.7.0 添加了 reset.css - 之后如何应用 CSS?
- mongodb - 在聚合中结合匹配过滤器
- java - 我正在尝试交换两个值,同时运行代码时出现此错误“不兼容的类型。找到:'int',需要:'int[]'”
- tensorflow - 如何将训练过程集成到不基于反向传播的 keras 中?