首页 / PHP / PHP Regex帮助来解析字符串
PHP Regex帮助来解析字符串
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP Regex帮助来解析字符串,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2217字,纯文字阅读大概需要4分钟。
内容图文
![PHP Regex帮助来解析字符串](/upload/InfoBanner/zyjiaocheng/652/208eaf2bda9249668eb9bbd9d48fb9f5.jpg)
我有一个如下字符串:
Are you looking for a quality real estate company?
<s>Josh's real estate firm specializes in helping people find homes from
[city][State].</s>
<s>Josh's real estate company is a boutique real estate firm serving clients
locally.</s>
In [city][state] I am sure you know how difficult it is
to find a great home, but we work closely with you to give you exactly
what you need
我想将此段基于< s>拆分为一个数组< / s>标签,因此我得到以下数组:
[0] Are you looking for a quality real estate company?
[1] Josh's real estate firm
specializes in helping people find homes from [city][State].
[2] Josh's real estate company is a boutique real estate firm serving clients
locally.
[3] In [city][state] I am sure you know how difficult it is
to find a great home, but we work closely with you to give you exactly
what you need
这是我当前正在使用的正则表达式:
$matches = array();
preg_match_all(":<s>(.*?)</s>:is", $string, $matches);
$result = $matches[1];
print_r($result);
但这仅返回一个数组,其中包含在< s>之间找到的文本. < / s>标签,它将忽略在这些标签之前和之后找到的文本. (在上面的示例中,它将仅返回数组元素1和2.
有任何想法吗?
解决方法:
我能得到的最接近的是使用preg_split():
$string = <<< STR
Are you looking for a quality real estate company? <s>Josh's real estate firm
specializes in helping people find homes from [city][State].</s>
<s>Josh's real estate company is a boutique real estate firm serving clients
locally.</s> In [city][state] I am sure you know how difficult it is
to find a great home, but we work closely with you to give you exactly
what you need
STR;
print_r(preg_split(':</?s>:is', $string));
并得到以下输出:
Array
(
[0] => Are you looking for a quality real estate company?
[1] => Josh's real estate firm
specializes in helping people find homes from [city][State].
[2] =>
[3] => Josh's real estate company is a boutique real estate firm serving clients
locally.
[4] => In [city][state] I am sure you know how difficult it is
to find a great home, but we work closely with you to give you exactly
what you need
)
除非产生额外的数组元素(索引2),否则在片段[city] [State]之间存在换行符.和< s> Josh的房地产公司.
虽然添加一些代码以删除空格匹配是微不足道的,但是我不确定您是否希望这样做.
内容总结
以上是互联网集市为您收集整理的PHP Regex帮助来解析字符串全部内容,希望文章能够帮你解决PHP Regex帮助来解析字符串所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。