0

I have a string as below

$str = '"Mark Zuckerberg" facebook "A social utility connecting friends" profile';

I want it to be manipulated as follows

$output = '"Mark Zuckerberg" OR facebook OR "A social utility connecting friends" OR profile';

What I am trying to have in output is all the units combined with OR in between them. Here a unit is wither a single word when its not in double quotes or the complete string that falls within the single quotes.

I wanted to try with preg_replace. But am unable to get a correct regular expression to match. Kindly help!

2 Answers 2

3
$result = preg_replace('/ (?=(?:[^"]*"[^"]*")*[^"]*$)/', ' OR ', $subject);

works if you don't have any escaped quotes in your string. It replaces spaces only if they are followed by an even number of double quotes.

Sign up to request clarification or add additional context in comments.

Comments

0

Any reason why preg_replace rather than a simple

$output = '"'.implode('" OR "',str_getcsv($str,' ')).'"';

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.