I have a giant string and I want to delete all substrings within that string that start with a particular set of characters, in this case (' http) and end with a space. Framed differently, I want to delete all words (urls) that begin with (' http) - note the space as I have urls that begin with a parenthesis that I don't want to delete e.g., '(http..)' So far what I have looks like this but I'm not sure if regex is a better option here?
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
}
You can do this with preg_replace. The following does exactly what you described:
preg_replace('/ (http[^ ]*) /', ' ', $string);
This version will also remove the urls if they occur at the very beginning and/or very end of the string:
preg_replace('/(^| )(http[^ ]*)( |$)/', ' ', $string);
Or you may want to use any/all whitespace as delimiters, rather than just a space character, like so:
preg_replace('/(^|\s+)(http\S*)(\s+|$)/', ' ', $string);