简体   繁体   中英

Remove all numbers from a string unless they follow a certain character in 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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM