加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 仅在爆炸匹配的最后一次出现时爆炸字符串

发布时间:2020-12-13 21:55:34 所属栏目:PHP教程 来源:网络整理
导读:我试图爆炸一个字符串,但我需要它只在最后’和’而不是每个’和’爆炸.有没有办法做到这一点? ?php$string = "one and two and three and four and five";$string = explode(" and ",$string);print_r($string);? ?结果: 数组([0] =一[1] =二[2] =三[3] =
我试图爆炸一个字符串,但我需要它只在最后’和’而不是每个’和’爆炸.有没有办法做到这一点?

<?php

$string = "one and two and three and four and five";
$string = explode(" and ",$string);

print_r($string);

?>

?结果:

数组([0] =>一[1] =>二[2] =>三[3] =>四[4] =>五)

?需要结果:

数组([0] =>一,二,三,四[1] =>五)

解决方法

我的方法更简单,使用preg_match_all()和简单的正则表达式:

$string = "one and two and three and four and five";
$pattern = '/(w+s)+/';
preg_match_all($pattern,$string,$matches);

$length = strlen($matches[0][0]);

echo $matches[0][0]; // 'one and two and three and four and'
echo substr($string,$length); // 'five'

这里唯一的问题是第一个匹配仍然有一个尾随’和’,如果需要,可以通过一些简单的编码来摆脱它.如果你想要更复杂的正则表达式,你可以使用积极的前瞻和消极的外观.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读