Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

If I have a string that equals "firstpart".$unknown_var."secondpart", how can I delete everything between "firstpart" and "secondpart" (on a page that does not know the value of $unknown_var)?

Thanks.

Neel

share|improve this question
1  
Specify the pattern of the string contained in $unknown_var –  Dor Jul 26 '11 at 23:22

3 Answers 3

up vote 2 down vote accepted

substr_replace

start and length can be computed with strpos. Or you could go the regex route if you're comfortable learning about them.

share|improve this answer
1  
substr_replace is substantially faster than regex (although less pretty). Upvoted. –  Chris Jul 26 '11 at 23:37
    
Agreed. I've never much cared for the regex holy wars that go on... –  colithium Jul 26 '11 at 23:39
1  
@Neel: If you actually have a variable "$unknown_var", you could simply do "str_replace($unknown_var,'',$str);", but I assume you just used that to ask your question. Go with Colithium's answer :-) –  Chris Jul 26 '11 at 23:41
    
@Chris: One more question: how do I use substr_replace? I tried doing $data = substr_replace($old_data, '', $strpos1, $strpos2) but it deleted too much. I added the length of "firstpart" to $strpos1. $strpos1 is 250 and $strpos2 is 520. –  Neel Jul 27 '11 at 21:36
    
The argument list is substr_replace([string],[replacement],[starting position], [length]), so in your case, it should be: $data = substr_replace($old_data,'',$strpos1,$strpos2-$strpos1); –  Chris Jul 27 '11 at 22:40

As long as $unkonwn_var does not contain neither firstpart nor secondpart, you can match against

firstpart(.*)secondpart

and replace it with

firstpartsecondpart
share|improve this answer

You shoukd use a regexp to do so.

preg_replace('/firspart(.*)secondpart/','firstpartsecondpart',$yourstring);

will replace anything between the first occurence of firstpart and the last of secondpart, if you want to delete multiple time between first and second part you can make the expression ungreedy by replacing (.*) by (.*?) in the expression

preg_replace('/firspart(.*?)secondpart/','firstpartsecondpart',$yourstring);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.