我有一个以字符串形式存储的文本正文。我想用子字符串的子字符串替换多个子字符串。这是我想要替换的典型子字符串(请注意,我想要替换多个子字符串)。
$String = "loads of text [[gibberish text|Text i Want]] more text [[gibberish text|Text i Want]] more text [[if no separator then just remove tags]]";
$String = deleteStringBetweenStrings("[[", "|", $String , true);
deleteStringBetweenStrings是一个递归函数,它将删除2个子串(包括子串)之间的所有代码,这将完成我想要的第一个子串,但在此之后会有点疯狂。
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;
}
我有更有效的方法吗?
预期输出=“文本载入文本我想要更多文本文本我想要更多文本,如果没有分隔符,那么只需删除标签”
答案 0 :(得分:1)
仅限正则表达式和正则表达式....
只需使用以下正则表达式匹配您不需要的文本,然后将其替换为空字符串。
(?<=\[\[)(?:(?!\]]|\|).)*\||\[\[|\]\]
<强>代码:强>
<?php
$str = "loads of text [[gibberish text|Text i Want]] more text [[gibberish text|Text i Want]] more text [[if no separator then just remove tags]]";
echo preg_replace("/(?<=\[\[)(?:(?!\]]|\|).)*\||\[\[|\]\]/m", "", $str);
?>
<强>输出:强>
loads of text Text i Want more text Text i Want more text if no separator then just remove tags
我怎么弄明白?
(?<=\[\[)
照看[[
个符号。(?:(?!\]]|\|).)*
匹配任何字符,但不能匹配]]
或|
符号的任何字符。\|
文字|
符号。这可确保匹配在到达右括号|
之前必须包含]]
符号gibberish text|
字符串类型中的[[gibberish text|Text i Want]]
,并且不会触及此[[if no separator then just remove tags]]
|
或\[\[
现在匹配[[
|
或\]\]
符号。删除所有匹配的字符将为您提供所需的输出。答案 1 :(得分:1)
这样的事情应该可以解决问题(同时保留添加自己的开始和结束字符串的能力):
function deleteStringBetweenStrings($start, $end, $string) {
// create a pattern from the input and make it safe to use in a regular expression
$pattern = '|' . preg_quote($start) . '(.*)' . preg_quote($end) . '|U';
// replace every occurrence of this pattern with an empty string in full $string
return preg_replace($pattern, '', $string);
}
$String = "loads of text [[gibberish text|Text i Want]] more text [[gibberish text|Text i Want]] more text [[if no separator then just remove tags]]";
$String = deleteStringBetweenStrings("[[", "|", $String);
答案 2 :(得分:0)
试试这个:
$string = 'loads of text [[gibberish text|Text i Want]] more text [[gibberish text|Text i Want]] more text [[if no separator then just remove tags]]';
function doReplace($matches) {
$str = $matches[2];
if (strpos($str, '|')) {
$parts = explode('|', $str);
return $parts[1];
} else {
return $str;
}
}
echo preg_replace_callback('/(\[\[(.*?)\]\])/', 'doReplace', $string);
它回应
loads of text Text i Want more text Text i Want more text if no separator then just remove tags
我认为这正是你想要的!