
Question:
How can I remove the <strong>first</strong> instance of a certain piece of html from a string.
I'm looking to remove
</tr>
</table></td>
</tr
which is near the begining, but it also appears throughout the string.
I also need a way to do the same thing but the <strong>last</strong> instance of it.
Anyone know?
Answer1:if you know roughly how close to the end of the string the substring that you want to replace is, you use substr_replace()
with a negative $start
and $length
parameters, or you could just code up a function by hand to actually go through, find the last occurrence, then delete it. something like this (untested, written very quickly):
function replace_last_occurrence($haystack, $needle) {
$pos = 0;
$last = 0;
while($pos !== false) {
$pos = strpos($haystack, $needle, $pos);
$last = $pos;
}
substr_replace($haystack, "", $last, strlen($needle));
}
similar, for first occurrence
function replace_first_occurrence($haystack, $needle) {
substr_replace($haystack, "", strpos($haystack, $needle, $pos),
strlen($needle));
}
you could also generalize this to replace the nth occurrence:
function replace_nth_occurrence($haystack, $needle, $n) {
$pos = 0;
$last = 0;
for($i = 0 ; $i <= $n ; $i++) {
$pos = strpos($haystack, $needle, $pos);
$last = $pos;
}
substr_replace($haystack, "", $last, strlen($needle));
}
Answer2:simplest way is to explode/split the string shift the top and pop the last then implode what's left with you're separator and concatenate the three.. i.e.:
$separator = 'your specified html separator here';
$bits = explode($separator , $yourhtml );
$start = array_shift($bits);
$end = array_pop($bits);
$sorted = $start . implode($separator,$bits) . $end;
(not tested)
Answer3:This will delete last occurrence:
$needle = <<<EON
</tr>
</table></td>
</tr
EON;
if(preg_match('`.*('.preg_quote($needle).')`s', $haystack, $m, PREG_OFFSET_CAPTURE)) {
$haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0]));
}
As additional bonus you may ignore varying number of whitespaces within searched fragment like this:
if(preg_match('`.*('.implode('\s+', array_map('preg_quote', preg_split('`\s+`', $needle))).')`s', $haystack, $m, PREG_OFFSET_CAPTURE)) {
$haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0]));
}
Or even search case-insensitively by adding i-flag to regexp:
if(preg_match('`.*('.implode('\s+', array_map('preg_quote', preg_split('`\s+`', $needle))).')`is', $haystack, $m, PREG_OFFSET_CAPTURE)) {
$haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0]));
}
Answer4:You'll be wanting <a href="http://php.net/manual/en/function.str-replace.php" rel="nofollow">str_replace</a>. Replace that section with empty space (eg:"")