Reputation: 629
I'm trying to replace some words in my string for a white space, but the words that I try to replace are different all the time, except for the first 3 characters. For example I have this string:
"Hello, my name is Lorum and toc341013697 I'm 29 years old. And I toc241053612 test and bla h blah blah toc410183666."
I would like to remove the words starting with toc
. The numbers behind toc
are always different, but they are always 9 characters long.
Is there a way to do this? I tried this:
$text = "Hello, my name is Lorum and toc341013697 I'm 29 years old. And I toc241053612 test and bla h blah blah toc410183666.";
$toc = substr($text, strpos($text, "toc") + strlen("toc"), 9);
$toc = "toc".$toc." ";
$find = array($toc);
$replace = array("");
$text = str_replace($find, $replace, $text);
But the he only removes the first toc.
Upvotes: 0
Views: 142
Reputation: 15213
You can use preg_replace
to replace multiple strings that are similar using a regular expression:
$text = "Hello, my name is Lorum and toc341013697 I'm 29 years old. And I toc241053612 test and bla h blah blah toc410183666.";
$text = preg_replace('/toc[0-9]{9}/','', $text);
outputs:
Hello, my name is Lorum and I'm 29 years old. And I test and bla h blah blah .
The regular expression toc[0-9]{9}
will replace every occurence of "toc" with exactly 9 digits behind it.
Upvotes: 2
Reputation: 1573
$string = "Hello, my name is Lorum and toc341013697 I'm 29 years old. And I toc241053612 test and bla h blah blah toc410183666.";
$pos = 0;
while(($pos = strpos($string, 'toc', $pos)) !== false){
$end = $pos + 13;
for($i = $pos; $i < $end; $i++){
$string[$i] = '';
}
$pos += strlen('toc');
}
print $string; // Hello, my name is Lorum and I'm 29 years old. And I test and bla h blah blah
Upvotes: 0