Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all numbers from a string unless they follow a certain character in PHP

Tags:

string

regex

php

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);
like image 818
astrox Avatar asked Jan 27 '23 08:01

astrox


1 Answers

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

like image 154
scrowler Avatar answered Jan 30 '23 05:01

scrowler