0

I have a question. I need to add a + before every word and see all between quotes as one word.

A have this code

preg_replace("/\w+/", '+\0', $string);

which results in this

+test +demo "+bla +bla2"

But I need +test +demo +"bla bla2"

Can someone help me :) And is it possible to not add a + if there is already one? So you don't get ++test

Thanks!

CodeLove
  • 462
  • 4
  • 14
Henk de Boer
  • 139
  • 14

2 Answers2

1

I can't test this but could you try it and let me know how it goes?

First the regex: choose from either, a series of letters which may or may not be preceded by a '+', or, a quotation, followed by any number of letters or spaces, which may be preceded by a '+' followed by a quotation.

I would hope this matches all your examples.

We then get all the matches of the regex in your string, store them in the variable "$matches" which is an array. We then loop through this array testing if there is a '+' as the first character. If there is, do nothing, otherwise add one.

We then implode the array into a string, separating the elements by a space.

Note: I believe $matches in created when given as a parameter to preg_match.

$regex = '/[((\+)?[a-zA-z]+)(\"(\+)?[a-zA-Z ]+\")]/';

preg_match($regex, $string, $matches);

foreach($matches as $match)
{
    if(substr($match, 0, 1) != "+") $match = "+" + $match;
}

$result = implode($matches, " ");
AndrewB
  • 764
  • 1
  • 6
  • 25
1

Maybe you can use this regex:

$string = '+test demo between "double quotes" and between \'single quotes\' test';
$result = preg_replace('/\b(?<!\+)\w+|["|\'].+?["|\']/', '+$0', $string);
var_dump($result);

// which will result in:

string '+test +demo +between +"double quotes" +and +between +'single quotes' +test' (length=74)

I've used a 'negative lookbehind' to check for the '+'. Regex lookahead, lookbehind and atomic groups

Community
  • 1
  • 1
The fourth bird
  • 154,723
  • 16
  • 55
  • 70