4

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

4 Answers 4

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

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

4
  • I agree, use str_replace. It is much faster than using a regex. Sep 17, 2010 at 14:26
  • 4
    as this but use the strings " ELLER " and " OR " (note spaces)
    – Segfault
    Sep 17, 2010 at 14:27
  • Heed Segfault's advice, otherwise a search for "Helen Keller" or "Uri Geller" won't work as expected
    – Mark Baker
    Sep 17, 2010 at 14:29
  • @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. Sep 17, 2010 at 14:36
7

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);
0

Should note too that you can also pass str_replace an array of values to change and an array of values to change to such as:

str_replace(array('item 1', 'item 2'), 'items', $string);

or

str_replace(array('item 1', 'item 2'), array('1 item', '2 item'), $string);

0
<?php
// data
$name = "Daniel";
$order = 132456;

// String to be searched
$string = "Hi [name], thank you for the order [order_id]. The order is for [name]";

// replace rules - replace [name] with $name(Danile) AND [order_id] with $order(123456)
$text_to_send = str_replace(array('[name]', '[order_id]'), array($name, $order), $string);

// print the result
echo $text_to_send;

"Hi Damiel, thank you for the order 123456. The order is for Daniel"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.