regex - Dynamically Replace Substring With Substring Using PHP -
i have body of text stored string. there multiple substrings want replace substring of substring. typical substring want replace (note there multiple substrings want replace).
$string = "loads of text [[gibberish text|text want]] more text [[gibberish text|text want]] more text [[if no separator remove tags]]"; $string = deletestringbetweenstrings("[[", "|", $string , true);
deletestringbetweenstrings recursive function delete code between 2 substrings (including substrings) want first substring goes bit crazy after this.
function deletestringbetweenstrings($beginning, $end, $string, $recursive) { $beginningpos = strpos($string, $beginning); $endpos = strpos($string, $end); if ($beginningpos === false || $endpos === false) { return $string; } $texttodelete = substr($string, $beginningpos, ($endpos + strlen($end)) - $beginningpos); $string = str_replace($texttodelete, '', $string); if (strpos($string, $beginning) && strpos($string, $end) && $recursive == true) { $string = deletestringbetweenstrings($beginning, $end, $string, $recursive); } return $string; }
is there more efficient way me this?
expected output = "loads of text text want more text text want more text if no separator remove tags"
something should trick (whilst preserving ability add own start , end strings):
function deletestringbetweenstrings($start, $end, $string) { // create pattern input , make safe use in regular expression $pattern = '|' . preg_quote($start) . '(.*)' . preg_quote($end) . '|u'; // replace every occurrence of pattern empty string in full $string return preg_replace($pattern, '', $string); } $string = "loads of text [[gibberish text|text want]] more text [[gibberish text|text want]] more text [[if no separator remove tags]]"; $string = deletestringbetweenstrings("[[", "|", $string);
Comments
Post a Comment