简体   繁体   English

在条件下替换字符串(正则表达式?)

[英]Replace a string under condition (Regex?)

I am looking for a solution for search and replace.我正在寻找搜索和替换的解决方案。 I would need to add an empty space after specific string BUT only if there isn't one already.我需要在特定字符串之后添加一个空格,但只有在没有空格时才需要。 Regular expressions are to advanced for me.正则表达式对我来说是先进的。 Anyone wants to help me out?有人想帮我吗?

For example例如

Lorem ipsum[something]abcdefg[/something]dolor sit amet

Needs to be replace with需要替换为

Lorem ipsum[something]abcdefg[/something] dolor sit amet

So, I need to search for [/something] and if it is not followed by space, then do the replace...所以,我需要搜索[/something] ,如果后面没有空格,则进行替换...

The regular expression can be this:正则表达式可以是这样的:

/(\[\/something\])(?!\s)/gmi

You can test it and know the whole explanation here:您可以测试它并在此处了解整个解释:

https://regex101.com/r/pC4pQ3/1 https://regex101.com/r/pC4pQ3/1

If you see the first is targetted because is not an space, but the second is the opposite.如果你看到第一个被定位,因为不是空格,但第二个是相反的。

To apply this in PHP you must to use preg_replace() .要在 PHP 中应用它,您必须使用preg_replace() Something like this:像这样的东西:

$string = "Lorem ipsum[something]abcdefg[/something]dolor sit amet";
echo preg_replace("/(\[\/something\])(?!\s)/", "\1 ", $string);
// result: "Lorem ipsum[something]abcdefg[/something] dolor sit amet"

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

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