1

I have a long string that has imbedded in it: "ABC_1_" and "ABC_2_" and "ABC_3_" etc.

For example:

"lorum ipsum ABC_1_ doit more ABC_3_ and so on".

I need to write a PHP preg_replace that will remove the 6 characters (ABC_xx) if the first 4 are "ABC_" and return the full remaining string, in my example:

"lorum ipsum  doit more  and so on". 

Thanks!

2 Answers 2

3

Use preg_replace with regular expression: (ABC_.{2} )

$string = "lorum ipsum ABC_1_ doit more ABC_3_ and so on";
$pattern = "/(ABC_.{2})/";
$replacement = "";
echo preg_replace($pattern, $replacement, $string);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Nice bass clef icon!
Id didn't know what's it called. Now I know :)
2

Try this:

$s = preg_replace('/\bABC_../', '', $s);

The \b matches a word boundary, and the dots match any character (apart from new line).

Full example:

<?php
$s = 'ABC_1_foo lorum ipsum ABC_1_ doit more ABC_3_ and so on'; 
$s = preg_replace('/\bABC_../', '', $s);
echo $s;
?>

Result:

foo lorum ipsum  doit more  and so on

(ideone)

2 Comments

this works. I removed the \b because the phrase may not be on a word boundary. But I didn't specify that in my question. THANKS!!!
@sdfor: The reason for the word boundary was so that it doesn't accidentally match DABC_D_. But if you want that to match then yes you don't need the word boundary.

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.