Let's say I have numerous strings where the characters do not have predefined positions.....
$string = '324 Example words #25 more words';
$string2 = 'Sample words 324 Example words #25 more words #26';
I would like to remove all the numbers in a php string, unless they immediately follow a '#' character. There are lots of posts about removing parts of a string after a character, but I want to keep only the numbers that follow a certain character until the next blank space. The above sample strings should look like this...
$string = 'Example words #25 more words';
$string2 = 'Sample words Example words #25 more words #26';
Is it possible? Could this be accomplished with regex? How can I modify the following code snippet to accomplish this?
$string = preg_replace('/[0-9]+/', '', $string);
You can use a combination of a word boundary, and a negative lookbehind to say "capture any set of numbers that aren't preceded by a #":
$string = preg_replace('/\b(?<!#)(\d+)/', '', $string);
If you also want to remove the space after the numbers:
$string = preg_replace('/\b(?<!#)(\d+\s)/', '', $string);
Example: https://www.phpliveregex.com/p/psK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With