Remove first and last instance of a string?
How can I remove the first 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 t开发者_StackOverflow中文版he same thing but the last instance of it.
Anyone know?
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));
}
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)
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]));
}
You'll be wanting str_replace. Replace that section with empty space (eg:"")
精彩评论