Ranjitha
Ranjitha

Reputation: 83

How to use search and replace all the matching words in a sentence in php

I have to search and replace all the words starting with @ and # in a sentence. Can you please let me know the best way to do this in PHP. I tried with

preg_replace('/(\@+|\#+).*?(?=\s)/','--', $string);

This will solve only one word in a sentence. I want all the matches to be replace.

I cannot g here like in perl.

Upvotes: 3

Views: 674

Answers (3)

Prasanth Bendra
Prasanth Bendra

Reputation: 32810

Try this :

  $string     = "@Test let us meet_me@noon see #Prasanth";
  $new_pro_name = preg_replace('/(?<!\S)(@\w+|#\w+)/','--', $string);
  echo $new_pro_name;

This replaces all the words starting with @ OR #

Output: -- let us meet_me@noon see --

If you want to replace word after @ OR # even if it at the middle of the word.

  $string     = "@Test let us meet_me@noon see #Prasanth";
  $new_pro_name = preg_replace('/(@\w+|#\w+)/','--', $string);
  echo $new_pro_name;

Output: -- let us meet_me-- see --

Upvotes: 1

user1919238
user1919238

Reputation:

preg_replace replaces all matches by default. If it is not doing so, it is an issue with your pattern or the data.

Try this pattern instead:

(?<!\S)[@#]+\w+

(?<!\S) - do not match if the pattern is preceded by a non-whitespace character.

[@#]+ - match one or more of @ and #.

\w+ - match one or more word characters (letter, numbers, underscores). This will preserve punctuation. For example, @foo. would be replaced by --.. If you don't want this, you could use \S+ instead, which matches all characters that are not whitespace.

Upvotes: 2

SteeveDroz
SteeveDroz

Reputation: 6156

A word starting with a character implies that it has a space right before this character. Try something like that:

/(?<!\S)[@#].*(?=[^a-z])/

Why not use (?=\s)? Because if there is some ponctuation right after the word, it's not part of the word. Note: you can replace [^a-z] by any list of unallowed character in your word.

Be careful though, there are are two particular cases where that doesn't work. You have to use 3 preg_replace in a row, the two others are for words that begin and end the string:

/^[@#].*(?=[^a-z])/
/(?<!\S)[@#].*$/

Upvotes: 1

Related Questions