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.
Need to subtract 1 string from another...
Moderator: General Moderators
- aceconcepts
- DevNet Resident
- Posts: 1424
- Joined: Mon Feb 06, 2006 11:26 am
- Location: London
Re: Need to subtract 1 string from another...
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.
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...
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?
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?
- aceconcepts
- DevNet Resident
- Posts: 1424
- Joined: Mon Feb 06, 2006 11:26 am
- Location: London
Re: Need to subtract 1 string from another...
I get you now
This is how one might approach it:
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.
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);
This is quite a methodical approach. You should be able to do this using regex also.