简体   繁体   中英

How to replace all matches with Regex / PHP / preg_replace

basically I want to replace all words like : test , someword , bleble .

The problem is that regex I am using, only replaces one of the words, first one which is found . Can anyone help me with this one?

$string = 'http://nu/style/test/someword/bleble';
preg_replace('/(test|someword|bleble)/','',$string);

Best Regards, Mateusz

You can use an array to solve the problem.

$string  = "http://nu/style/test/someword/bleble";
$remove = array("/test/", "someword/", "bleble");

$result = str_replace($remove, ' ', $string);

You can use array() for your patterns. You need one array for the patterns, which may be replaced and another array for replacements.

$string = 'http://nu/style/test/someword/bleble';
$patterns = array(
  "/test/",
  "/someword/",
  "/bleble/"
);

$replacements = array(
  "",
  "",
  ""
);

preg_replace($patterns, $replacements, $string);

Of course, if you want to replace all the $patterns with the same word, you can use:

preg_replace($patterns, " ", $string);

OUTPUT: http://nu/style///

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM