正则表达式 - 如何用 PHP 替换字符串的最后 3 个单词 [英] Regex - How to replace the last 3 words of a string with PHP

查看:28
本文介绍了正则表达式 - 如何用 PHP 替换字符串的最后 3 个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试用 标签包裹最后 3 个单词

Trying to wrap the last 3 words in a <span> tag

$str = 'Lorem ipsum dolor sit amet';
$h2 = preg_replace('/^(?:\w+\s\w+)(\s\w+)+/', '<span>$1</span>', $str);

推荐答案

这里是:

$h2 = preg_replace('/(\w+\s\w+\s\w+)$/', '<span>$1</span>', $str);

从最后三个字开始,让左边(从头开始)打开以进行匹配.

Since its last three words, so make the left side(from begin) as open to have the match.

这篇关于正则表达式 - 如何用 PHP 替换字符串的最后 3 个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆