2

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...

7
  • What's the language? Commented Mar 9, 2016 at 16:08
  • Sorry, I didn't know Regex is tied to language, it is PHP or executing mySql statement Commented Mar 9, 2016 at 16:21
  • MySQL statement sure not. I will remove that tag. Commented Mar 9, 2016 at 16:22
  • 2
    Regex is not tied to language, but the way you replace all occurrences is. In Java, you'd write something like s.replaceAll("yourregex", "new value"). In javascript would be something like s.replace(/yourregex/g, RegExp.$1...) Commented Mar 9, 2016 at 16:24
  • @BorisKozarac my answer solves your problem, for sure. Try it and tell us :) Commented Mar 9, 2016 at 16:43

1 Answer 1

2

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

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(). 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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.