使用 Preg_Replace 保留删除的值
我正在使用 preg_replace 从字符串中删除一些内容。我想知道是否有一种方法可以将删除的内容保留在不同的变量中。这是我正在使用的:
$city = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $content[2]);
I am using preg_replace to remove some content from a string. What I am wondering is if there is a way to keep the stuff that is removed in a different variable. Here is what I am using:
$city = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $content[2]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先使用 preg_match_all() 获取字符串中的所有匹配项,然后运行 preg_replace() 进行实际替换。
First get all the matches in your string with preg_match_all() and then run preg_replace() to do the actual replacing.
首先运行 preg_match() 来获取要替换的内容,然后按照您的操作替换内容。
Run a preg_match() first to get the content which will be replaced, and then replace the content as you do.
您可以使用
preg_replace_callback
并在回调中替换它们之前将匹配项分配给变量:但是,在您的具体情况下,您甚至根本不需要运行
preg_replace
,您只需使用preg_match
>:You can use
preg_replace_callback
and assign the matches to variables before you replace them in your callback:However in your specific case, you don't even need to run
preg_replace
at all, you can just usepreg_match
: