Preg_replace to delete offline numbers

I want to replace all autonomous numbers from a string where the number has no adjacent characters (including dashes), for example:

Test 3 string 49Test 49test9 9

Should return test string 49Test 49Test9

So far I have played with:

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

However, with no luck, this returns

Test line 9Test 9test9

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

Thanks in advance

+6
source share
4 answers

Try using word boundaries and negative images for hyphens, for example

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

Not so difficult if you look at the spaces :)

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

Try this, I tried to satisfy your additional requirements, so as not to match 5-abc

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

and replace with one space !

See here online at Regexr

Then the task is to expand the boundary of the word with the symbol - . I achieved this using a negative look and looking - or \B (and not the word boundary)

In addition, I map the surrounding spaces to \s* , so you need to replace with one space.

+1
source

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

0
source

Source: https://habr.com/ru/post/901281/


All Articles