Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 344
user1041334 Avatar asked Nov 11 '11 09:11

user1041334


3 Answers

Try using a word boundary and negative look-arounds for hyphens, eg

$str = preg_replace('/\b(?<!-)\d+(?!-)\b/', '', $str);
like image 191
Phil Avatar answered Nov 19 '22 23:11

Phil


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;
like image 43
Berry Langerak Avatar answered Nov 20 '22 00:11

Berry Langerak


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.

like image 1
stema Avatar answered Nov 19 '22 22:11

stema