preg_replace 删除多个匹配项
我环顾四周但找不到合适的解决方案。
我有这个字符串,
$area = array("Some Text area 1", "Some Text area 2", "Some Text area 33", "Some Text area 40")
我想构造一个 preg_replace 来删除单词“area”和后面的 1 或 2 位数字。
我可以这样做来删除“区域 1”
$area = preg_replace('/area 1/','', $area);
我可以继续重复此操作以删除其他匹配项,但这不是很有效。
我可以仅用一个 preg_replace 删除该模式吗?
提前致谢
I have looked around but couldn't find an appropiate solution.
I have this string
$area = array("Some Text area 1", "Some Text area 2", "Some Text area 33", "Some Text area 40")
I want to construct a preg_replace that would remove the word "area" and the 1 or 2 digit number that follows.
I can do this to remove "area 1"
$area = preg_replace('/area 1/','', $area);
I can keep repeating this to remove other matches but it's not very efficiant.
Can I remove the pattern with just one preg_replace?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将删除所有包含文本“区域”后跟数字的匹配项。
Will remove all matches which have the text 'area' followed by a number.
使用以下方式指定至少一位数字:
preg_replace('/area [0-9]+/','', $area);
Specify atleast one digit with:
preg_replace('/area [0-9]+/','', $area);
您是否还想删除“区域”一词之前的空格?其代码是:
Do you also want to remove the space right before the word "area"? The code for that would be:
在搜索类似内容时发现了这篇文章:替换文本字符串中的多个术语。
因此,例如,我正在制作一个自动生成的下拉选择,并且选项基于文件名,我需要加载文件名并生成人类可读的文件名。
我的文件被命名为:temp_Event_Name.php
因此我必须删除“temp”、“_”和“.php”,以便有一个可选择的选项,该值将是要传递到后续表单的文件名这将使用该文件生成 PDF。
我发现使用
str_replace
。所以完整的代码是
:
$files 是一个包含文件名的数组,我是通过以下方式获得的:
显然需要额外的格式化才能将其放入我建议的 html 中,但这很容易。希望它能帮助@jamester 或遇到此问题的任何其他人。
Came across this post while searching for something similar: replace multiple terms in a text string.
So, for example I was making a automatically generated drop down select, and the options were based on filenames and I needed to load the filenames and generate a human readable filename as well.
My files were named: temp_Event_Name.php
So I had to remove the "temp", "_", and the ".php" so that there would be a selectable option, the value would be the filename to be passed onto a subsequent form which would use the file to generate a PDF.
What I found was to use
str_replace
.So the full code would be:
Where
$files is an array with the filenames, which I obtained through:
Obviously extra formatting is needed to get it into the html I've proposed, but that's easy. Hope it helps @jamester or anyone else who comes across this.