我有这个字符串:
$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 :(得分:2)
答案 1 :(得分:1)
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);
答案 2 :(得分:1)
不确定为什么你真的想要正则表达式,但这是一个解决方案
@Test
public void testYearOptions() throws Exception{
LocalDate date = LocalDate.of(2015,11,12);
PowerMockito.mockStatic(LocalDate.class);
Mockito.when(LocalDate.now()).thenReturn(date);
Map<String, String> semesterMap = Utilities.getYears(); //Your function where LocalDate is Uses
assertNotNull(yearsMap.get("2015"));//your assertion
}
它会捕获$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
之后的所有内容。换句话说 - 3组。
end
和start
之间的部分应为end
- 修剪。其他部分应该留在那里,所以我们只是恢复它们。
我相信使用e
答案 3 :(得分:1)
使用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”中删除,直到字符串结束。