Helpful Information
 
 
Category: PHP
Insert a string into a string

I have a string which I want to search through for a given expression. If I find this expression I want to insert a new string behind it. How do I do this?

To clarify things, here's what I have in mind:

$string = "blah something blah";
$expression = "something";
$insertvalue = "else";

search through $string for $expression;

if($string contains $expression)
{
insert $insertvalue into $string ->behind<- $expression;
}

well



<?
$string = "wombats are harmless";
$expression = "harmless";
$insertvalue = " (mostly)";

if(strstr($string,$expression)){
$string=str_replace($expression,$expression.$insertvalue,$string);
}

echo $string;
?>


but so does



<?
echo str_replace($expression,$expression.$insertvalue,$string);
?>


not sure if there is a reason you want to actually scan to see if the string exists in the firstplace?

ok I've altered my code a bit so it works with str_replace. Only problem now is that str_replace replaces all occurrences of the search string with the replacement string. Is there a way to get it to only replace the first occurence of the search string?

I tried this:

preg_replace($expression,$expression.$insertvalue,$string,1);

always get errormessage saying that delimiter must be alphanumeric???????????

well using regex should be a last resort... but this works..



<?
$string = "wombats are harmless but not as harmless as llamas";
$expression = "harmless";
$insertvalue = " (mostly)";

$string=preg_replace("|$expression|",$expression.$insertvalue,$string,1);
echo $string;
?>

What you could do is...



<?
//-----------------------------------------------
$string = "wombats are harmless";
$expression = "harmless";
$insertvalue = " (mostly)";

$pieces = explode($expression,$string);
$mod_string = $pieces[0] . $expression . $insertvalue . $pieces [1];

$n = count($pieces);
for($i = 2;$i < $n;$i++)
{
$mod_string .= $expression . $pieces[$i]
}
//-----------------------------------------------
?>


...should work... havn't tried though.










privacy (GDPR)