View Full Version : Insert a string into a string
Pompiuses
06-26-2002, 09:09 AM
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?
Pompiuses
06-26-2002, 09:54 AM
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;
}
firepages
06-26-2002, 10:14 AM
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?
Pompiuses
06-26-2002, 10:31 AM
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?
Pompiuses
06-26-2002, 11:09 AM
I tried this:
preg_replace($expression,$expression.$insertvalue,$string,1);
always get errormessage saying that delimiter must be alphanumeric???????????
firepages
06-26-2002, 01:37 PM
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;
?>
Flamerule
06-26-2002, 01:44 PM
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.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.