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?
Announcement
Collapse
No announcement yet.
Insert a string into a string
Collapse
X
-
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
PHP Code:<?
$string = "wombats are harmless";
$expression = "harmless";
$insertvalue = " (mostly)";
if(strstr($string,$expression)){
$string=str_replace($expression,$expression.$insertvalue,$string);
}
echo $string;
?>
PHP Code:<?
echo str_replace($expression,$expression.$insertvalue,$string);
?>resistance is...
MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)
Comment
-
str_replace
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?
Comment
-
well using regex should be a last resort... but this works..
PHP Code:<?
$string = "wombats are harmless but not as harmless as llamas";
$expression = "harmless";
$insertvalue = " (mostly)";
$string=preg_replace("|$expression|",$expression.$insertvalue,$string,1);
echo $string;
?>resistance is...
MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)
Comment
-
What you could do is...
PHP Code:<?
//-----------------------------------------------
$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]
}
//-----------------------------------------------
?>I don't suffer from insanity, I enjoy every single minute of it!
Comment
Comment