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.

Member Avatar for iamthwee

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...

Member Avatar for diafol

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);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.