PHP函数删除字符串中某些字符之间的所有字符 [英] PHP function to delete all between certain character(s) in string
本文介绍了PHP函数删除字符串中某些字符之间的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对function delete_all_between($char1, $char2, $string)
感兴趣
会在给定的$ string中搜索$ char1和$ char2,如果找到,则从这两个字符之间的子字符串中清除$ string,其中包括 $ char1和$ char2本身.
I'm interested in function delete_all_between($char1, $char2, $string)
that will search given $string for $char1 and $char2 and, if such has been found, clear $string from substring between these two characters, including $char1 and $char2 itself.
示例:
$string = 'Some valid and <script>some invalid</script> text!';
delete_all_between('<script>', '</script>', $string);
现在,$ string应该只包含
Now, $string should contain just
'Some valid and text'; //note two spaces between 'and text'
有人可以快速解决吗?
推荐答案
<?php
$string = 'Some valid and <script>some invalid</script> text!';
$out = delete_all_between('<script>', '</script>', $string);
print($out);
function delete_all_between($beginning, $end, $string) {
$beginningPos = strpos($string, $beginning);
$endPos = strpos($string, $end);
if ($beginningPos === false || $endPos === false) {
return $string;
}
$textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);
return delete_all_between($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced
}
这篇关于PHP函数删除字符串中某些字符之间的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文