Page 1 of 1
Need to subtract 1 string from another...
Posted: Sat Aug 15, 2009 10:14 pm
by Wolf_22
I have a variable filled with content. This variable will be copied, renamed, and in turn, will have newer content added to it later on in the script.
What function should I use to subtract the content of the first variable from the content of the second variable? I was thinking it was str_replace(), but I'm not entirely sure this is the function I need for this operation.
Re: Need to subtract 1 string from another...
Posted: Sat Aug 15, 2009 10:31 pm
by aceconcepts
Can you give an example of the strings?
Are trying to subtract as in minus or extract?
str_replace() simply replaces a specified portion os a string with a given substitute.
Re: Need to subtract 1 string from another...
Posted: Sat Aug 15, 2009 11:15 pm
by Wolf_22
Sure.
Let's say variableA = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
Let's say variableB = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. ' (basically variableA, but repeated)
I want to subtract variableA from variableB, but only once (and not for however many times the match occurs). Get me?
Re: Need to subtract 1 string from another...
Posted: Sat Aug 15, 2009 11:57 pm
by aceconcepts
I get you now
This is how one might approach it:
Code: Select all
//get both variables
$var1 = "abc";
$var2 = "123 abc abc abc";
//get length of variable you wish to subtract from other variable
$var1_len = strlen($var1);
//now find the first occurrence of $var1
$var1_pos = strpos($var2, $var1);
//now remove $var1 from $var2
$new_var2 = substr_replace($var2, "", $var1_pos, $var1_len);
For more info on this look at:
http://us2.php.net/manual/en/function.s ... eplace.php and
http://us2.php.net/manual/en/function.strrpos.php
This is quite a methodical approach. You should be able to do this using regex also.