Log in

View Full Version : replace a string and put the replace string on a variable



regicidedelferoz
04-24-2012, 03:34 AM
good day everyone,.

i want to replace a string and put the replaced string on a variable,.

ex.

$str = 'this is the oRiGiNaL text';
$find = 'original';
$replace = 'replaced';

output:
$str = 'this is the replaced text'; //the normal output of replacing text

$original = 'oRiGiNaL'; //the replaced text will be moved to a new variable and it's format/case is remain


thanks in advance,.

-regicide del feroz

james438
04-24-2012, 09:15 AM
<?php
$str = 'this is the oRiGiNaL text';
$pattern='/original/is';
$replace='replaced';
preg_match($pattern, $str, $match);
$str=preg_replace($pattern,$replace,$str);
$original="$match[0]";
echo"$original<br>";
echo"$str";
?>
The above will find the first occurrence of your desired text and assign it to the variable $original. All of the occurrences of your desired text will be replaced with the replacement text.

From how you described your problem PCRE is the only way I can see to go.

regicidedelferoz
04-25-2012, 01:02 AM
thank you sir,.