0

Hi
I want to replace a word from text. I can do it with str_replace or str_ireplace. But I need more advance. for Example. my code is as below

<?php
$search_word=$_POST['gender'];
$subject="Men and Women both r part of the world";
echo str_ireplace($search_word, '<span style="background:#0F0">' . $search_word . '</span>',
            $subject)."<br/>";
echo str_replace($search_word, '<span style="background:#0F0">' . $search_word . '</span>',
            $subject)."<br/>";
$search_1=str_replace($search_word, '<span style="background:#0F0">' . $search_word . '</span>',
            $subject)."<br/>";
$search_2=str_ireplace($search_word, '<span style="background:#0F0">' . $search_word . '</span>',
            $search_1)."<br/>";
echo $search_2;
?>

in first echo it is showing Both 'Men' and 'men' background color changed but 'men' replaced to 'Men'
in second echo it is showing Onle 'Men' background color changed
in third echo it is showing Both 'Men' and 'men' background color changed but 'men' replaced to 'Men'

But I want that background color of both 'Men' & 'men' will be changed but word should be remain its original case.
here $_POST['gender'] may be 'men' or 'MEN' or 'mEn' or 'danIwEb' etc. (any word and any character)

is it possible? plz help me.

4
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by diafol
0

Regex seems overkill to me.

Convert both the input and output string to ALL lowercase then do the match. There is a function in PHP that does this...

1

To retain case, I think you have to use regex.

$txt = "Men and men and MEn and mEN and mEn and menopause";
$text = preg_replace("/(men)/i", '<span style="background:#5fc9f6">$1</span>', $txt);

You can discount words containing men with the \b (word boundary):

$txt = "Men and men and MEn and mEN and mEn and menopause";
$text = preg_replace("/\b(men)\b/i", '<span style="background:#5fc9f6">$1</span>', $txt);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.