0

I want to replace whole word in php. I found a code from the link below PHP string replace match whole word

I took code sample below from the above link.

$text = preg_replace('/\bHello\b/', 'NEW', $text);

but it is not working for me. I have a string like

3 OR ( 2 AND CreatedDate = LAST_N_DAYS:2 ) OR 4

After replace 2 using above code it becomes

3 OR ( Name = 'LAST WEEK' AND CreatedDate = LAST_N_DAYS:Name = 'LAST WEEK' ) OR 4. 

2 is replace for "LAST_N_DAYS:2" string also. I want to replace only 2 alone. If it is with any word it should not be replaced.

Community
  • 1
  • 1
user1808669
  • 75
  • 2
  • 2
  • 7

3 Answers3

0

To replace 2 with NEW:

$text = preg_replace('/\s2\s/',' NEW ',$test);
Tuim
  • 2,491
  • 1
  • 14
  • 31
  • Thanks, this is working but it is replacing with extra space. for example if str = 'this is 2 only'. and i am replacing 2=4, then the result is coming like 'this is 4only'. actually '2 ' is replacing. – user1808669 Dec 14 '12 at 07:54
  • Then put a space after 4 in the replacement string like I did with ' NEW ' – Tuim Dec 14 '12 at 07:55
0

If you only wants to replace first occurrence then add a limit:

// pattern, replacement, string, limit
$text = preg_replace('#2#U', 'NEW', $text, 1);

Or you can use below:

$text = preg_replace('#2\s(AND)#', 'NEW $1', $text);
user969068
  • 2,818
  • 5
  • 33
  • 64
  • This replaces all occurences of 2 with NEW. And in the second case only the first 2. The user wants to replace any standalone 2 in the string with something else. – Tuim Dec 14 '12 at 09:39
0

you can simple use

str_replace('2', "Name = 'LAST WEEK'", $string);
Igor Mancos
  • 314
  • 6
  • 15
  • In this case all 2 will be replaced. for example $str = '2 and 12'. if we replace 2=4, then output will be '4 and 14' not '4 and 12'. – user1808669 Dec 14 '12 at 09:25