我有这个字符串:
$str = "here is start of rage, also here is some text and here is the end of string";
// ^^^^^ ^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
现在我正在尝试删除此范围之间的所有e
字母:[ start
- end
]。好吧,我想要这个输出:
$newstr = "here is start of rag, also hr is som txt and hr is th end of string";
我该怎么做?
您可以组合子字符串和修剪函数。
使用子字符串存储字符串的三个部分:0 表示字符串的开始、开始到结束、结束到字符串的实际结尾。然后,您可以在中间部分使用修剪,然后输出这三个部分的串联。
带有preg_replace
和'G
锚点:
echo preg_replace('~(?:'G(?!'A)|'bstart'b)[^e]*'K(?:'Be|e(?!nd'b))~S', '', $str);
详:
~
(?:
'G(?!'A) # contiguous to the previous match, not at the start of the string
| # OR
'bstart'b # the word "start"
)
[^e]* # all that is not an "e"
'K # exclude all previous matched characters from the whole match
(?:
'Be # an "e" that is not the start of a word
| # OR
e(?!nd'b) # an "e" that is not followed by "nd"
)
~
S # the STUDY modifier that tries to improve non-anchored patterns
此模式一次查找一个"e"。找到单词"start"后,'G
锚点将强制下一个匹配项是连续的,因为它与前一个匹配项结束时的位置匹配。当到达单词"结束"时(?:'Be|e(?!nd'b))
失败并且连续性被破坏(直到另一个最终单词"开始")。
请注意,此模式不会检查字符串中是否存在单词"end"(但可以轻松完成)。如果单词"end"不存在,则所有"e"将从单词"start"中删除,直到字符串的末尾。
在这种情况下,Substr 和 str_replace 是你的选择
<?php
$str = "here is start of rage, also here is some text and here is the end of string";
// ^^^^^ ^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
$start = 8;
$end = 65;
$newStr =
substr($str, 0, $start).
str_replace('e', '', substr($str, $start, $finish - $start)) .
substr($str, $finish);
var_dump($newStr);
不知道为什么你真的想要正则表达式,但这里有一个解决方案
$str = "here is start of rage, also here is some text and here is the end of string";
preg_match_all("/(.*?)start(.*?)end(.*?)$/", $str, $matches);
$newstr = $matches[1][0] . "start" . str_replace("e", "", $matches[2][0]) . "end" . $matches[3][0];
var_dump($newstr);
它捕获start
之前的所有内容,start
和end
之间的所有内容,以及end
之后的所有内容。换句话说 - 3组。
start
和end
之间的部分应进行e
修剪。其他部分应该留在那里,所以我们只是恢复它们。
我相信使用preg_replace_callback
也可以实现