简体   繁体   English

正则表达式是什么?

[英]What would be the regex for this?

The variable $description which contains some text may also contain a string like so: 包含一些文本的$description变量也可能包含类似这样的字符串:

!some_text_that_may_be_different_each_time!

I need to get rid of these, so I tried: 我需要摆脱这些,所以我尝试:

$new_description = preg_replace("!.+?!", '', $description);

But no luck. 但是没有运气。 What would be a good way to get rid of these strings? 摆脱这些字符串的好方法是什么?

Also removing them may leave extra spaces. 同时删除它们可能会留下多余的空间。 For example: 例如:

Hi world how are ya !asdasdasdasdasd! blue chickens

would become 会成为

Hi world how are ya  blue chickens

As you can see now there are 2 spaces between ya and blue . 如您所见, yablue之间有两个空格。 I would like these to turn to one space as well. 我也希望这些也可以转到一个空间。

Try a regex like 尝试像这样的正则表达式

/![^!]+! */

note the " *" at the end to eat up any spaces after it. 请注意最后的“ *”会占用其后的所有空格。

Edit : Additionally, you didn't use the / / delimiters denoting the regex in your example, which is probably why your test didn't work. 编辑 :另外,您在示例中未使用表示正则表达式的/ /分隔符,这可能就是测试无效的原因。 I opted for [^!]+ (string not containing '!') instead of .+?, which is an ungreedy match, out of habit. 我出于习惯,选择了[^!] +(不包含'!'的字符串)而不是。+ ?,这是一个不愉快的匹配。 I'm not certain if it's faster or not, but in this example it probably doesn't matter. 我不确定它是否更快,但是在此示例中,这可能并不重要。

Try this: 尝试这个:

$new_description = preg_replace("/\s*![^!]+!/", '', $description);

If there is a space(s) before the ! 如果!之前有空格。 you will replace it, and therefore you will just have one space (the last one). 您将替换它,因此只有一个空间(最后一个)。
Notice that what you were doing is use "!" 请注意,您正在执行的操作是使用"!" as the delimiters of the regex and therefore it wasn't matching. 作为正则表达式的分隔符,因此不匹配。

There is actually a simple method. 实际上有一个简单的方法。 Just replace everthing in between exclamation points and then replace two spaces with one space. 只需替换感叹号之间的所有内容,然后用一个空格替换两个空格即可。

$new_description = preg_replace("!.*?!", '', $description);
$new_description = preg_replace(" +", ' ', $new_description);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM