2

I have content with tokens and want to strip all token which DOES NOT start with test. For example I have content:

$content = 'Hello [test:username]. What are you [token:name]';
$string = preg_replace('/\[test(.*)\]/', '', $content);

This work but replace with empty string all token which start with test. I want opposite which does not start with test and replace all another. How should I change regular expression. I want to get this result after preg_replace:

$content = 'Hello [test:username]. What are you';
1
  • Look at the regex docs, especially using ^ at the beginning of your pattern... Commented Apr 2, 2016 at 7:01

1 Answer 1

1

You can use the following regex

(?:\[test:[^]]+\])(*SKIP)(*F)|(?:\[\w[^]]+\])

So your code looks like as

preg_replace('/(?:\[test:[^]]+\])(*SKIP)(*F)|(?:\[\w[^]]+\])/', '', $content);

Explanation:

(?:\[test:[^]]+\]) // Will capture a group of tokens that have same 
                      pattern like as [test:...]

(*SKIP)(*F)        // This is supported by PCRE to skip the above captured group 

|(?:\[\w[^]]+\])   // This'll capture rest of the group that doesn't 
                     contains pattern like as [test:...]
Sign up to request clarification or add additional context in comments.

1 Comment

You're Welcome. Glad it helped you. @user3421014 I've also added an explanation too for future users

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.