如何匹配字符串中特定范围之间的特定字符?

时间:2016-03-17 00:34:37

标签: php regex

我有这个字符串:

$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";

我该怎么做?

4 个答案:

答案 0 :(得分:2)

您可以合并substringtrim个功能。

使用substring存储字符串的三个部分:0表示开始,从头到尾,结束字符串的实际结尾。然后你可以在中间部分使用trim,然后输出这三个部分的串联。

答案 1 :(得分:1)

Substrstr_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); 之前的所有内容,startstart之间的所有内容,以及end之后的所有内容。换句话说 - 3组。

endstart之间的部分应为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”中删除,直到字符串结束。

相关问题