PHP's preg_replace() function is not replacing all lines

PHP's preg_replace() function is not replacing all lines in:

12*some input
12*some input
1*some input

The code is:

preg_replace("/^(\d{1,2}[^0-9])/", "", $text);

The result is:

some input
12*some input
1*some input

But I want this:

some input
some input
some input
2

1 Answer

Depending on how the implementation of PHP does it, I think you're missing either an option or your regex doesn't do what you think it does.

/^(\d{1,2}[^0-9])/

The above regex would look for 1-2 numbers followed not by numbers from the start of the string. Depending on how it works a line break doesn't indicate that ^ should match again.

If you look at the PCRE Pattern Modifiers in the manual you likely need to supply the m flag to turn on multi line mode.

In addition, though it's missing from that manual page, you might need the global flag. So the above regex would become:

/^(\d{1,2}[^0-9])/gm

You might also be able to test this regular expression on platforms like RegEx 101.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like