0

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.

1
  • 1
    try preg_replace('/toc[0-9]{9}/','', $text); Your way will only remove the first one if you aren't even getting an error. Commented Jul 31, 2014 at 9:49

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
$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

2 Comments

That works too :) But I prefer the answer from @putvande, because I thinks it's easier to use ;)
I agree. I ought to use preg_replace a little more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.