search string for specific word and replace it

21,131

Solution 1

str_replace("ELLER", "OR", $string);

http://php.net/manual/de/function.str-replace.php

Solution 2

If you have a specific word you want to replace, there's no need for regex, you can use str_replace instead:

$string = str_replace("ELLER", "OR", $string);

When what you're looking for is not dynamic, using PHP's string functions will be faster than using regular expressions.

If you want to ensure that ELLER is only replaced when it is a full-word match, and not contained within another word, you can use preg_replace and the word boundary anchor (\b):

$string = preg_replace('/\bELLER\b/', 'OR', $string);
Share:
21,131
Imran Omer
Author by

Imran Omer

Visit: http://khanqah-daruslam.com/index.php

Updated on July 05, 2022

Comments

  • Imran Omer
    Imran Omer almost 2 years

    I think it is a regex I need.

    I have a text-input where users may search my website. They may use the word "ELLER" between search phrases, which is in english equal to "OR".

    My search engine however, requires it in english, so I need to replace all ELLER in the query string with OR instead.

    How can I do this?

    Btw, it is php...

    Thanks

  • Harold1983-
    Harold1983- over 13 years
    I agree, use str_replace. It is much faster than using a regex.
  • Segfault
    Segfault over 13 years
    as this but use the strings " ELLER " and " OR " (note spaces)
  • Mark Baker
    Mark Baker over 13 years
    Heed Segfault's advice, otherwise a search for "Helen Keller" or "Uri Geller" won't work as expected
  • Bruce
    Bruce over 13 years
    @Segfault Spaces aren't the only way to delineate a word (other possibilities are punctuation or the beginning or end of the string). You can't really effectively match only full words without regex.