简体   繁体   中英

preg_replace to remove stand-alone numbers

I'm looking to replace all standalone numbers from a string where the number has no adjacent characters (including dashes), example:

Test 3 string 49Test 49test9 9

Should return Test string 49Test 49Test9

So far I've been playing around with:

   $str = 'Test 3 string 49Test 49test9 9';
   $str= preg_replace('/[^a-z\-]+(\d+)[^a-z\-]+?/isU', ' ', $str);
   echo $str;

However with no luck, this returns

Test string 9Test 9test9

leaving out part of the string, i thought to add [0-9] to the matches, but to no avail, what am I missing, seems so simple?

Thanks in advance

尝试使用单词边界和负面环视作为连字符,例如

$str = preg_replace('/\b(?<!-)\d+(?!-)\b/', '', $str);

Not that complicated, if you watch the spaces :)

<?php
$str = 'Test 3 string 49Test 49test9 9';
$str = preg_replace('/(\s(\d+)\s|\s(\d+)$|^(\d+)\s)/iU', '', $str);
echo $str;

Try this, I tried to cover your additional requirement to not match on 5-abc

\s*(?<!\B|-)\d+(?!\B|-)\s*

and replace with a single space !

See it here online on Regexr

The problem then is to extend the word boundary with the character - . I achieved this by using negative look arounds and looking for - or \\B (not a word boundary)

Additionally I am matching the surrounding whitespace with the \\s* , therefore you have to replace with a single space.

I would suggest using explode(" ",$str) to get an array of the "words" in your string. Then it should be easier to filter out single numbers.

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