从给定字符串中删除以某些字符开头的所有子字符串

时间:2015-08-25 20:33:26

标签: php

我有一个巨大的字符串,我想删除该字符串中以特定字符集开头的所有子字符串,在本例中为('http)并以空格结尾。框架不同,我想删除以('http)开头的所有单词(网址) - 注意空格,因为我有一个以我不想删除的括号开头的网址,例如'(http ..)'所以我看起来像这样,但我不确定正则表达式是否是更好的选择?

while (strpos($body, ' http') !== false) {
      $beginningPos = strpos($body, ' http');
      $endPos = // somehow find the location of the first occurrence of a space after $beginningPos 
      // delete substring between $beginningPos and endPos
}

1 个答案:

答案 0 :(得分:0)

您可以使用preg_replace执行此操作。以下内容与您所描述的完全相同:

preg_replace('/ (http[^ ]*) /', ' ', $string);

如果网址出现在字符串的最开头和/或最后,该版本也将删除网址:

preg_replace('/(^| )(http[^ ]*)( |$)/', ' ', $string);

或者您可能希望将任何/所有空格用作分隔符,而不仅仅是空格字符,如下所示:

preg_replace('/(^|\s+)(http\S*)(\s+|$)/', ' ', $string);