PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to preg_replace all digits except specific numbers?

 November 20, 2022     preg-replace, regex     No comments   

Issue

It is necessary to clean a string from everything but English letters, spaces and specific numbers (eg 18,19,20 should be kept in the string).

Please help me with regex /([^a-zA-Z\s])/ to keep the specified numbers.


Solution

You can list the numbers that you want to keep between word boundaries for example and then make use of SKIP FAIL:

\b(?:1[89]|20)\b(*SKIP)(*F)|[^a-zA-Z\s]+

Rgex demo

$pattern = "/\b(?:1[89]|20)\b(*SKIP)(*F)|[^a-zA-Z\s]+/";
$s="test 18 119 19 50 20 #@$@#%";
echo preg_replace($pattern, "", $s);

Output

test 18  19  20 


Answered By - The fourth bird
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing