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.
CodePudding user response:
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]
$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
CodePudding user response:
Using the PREG_SPLIT_DELIM_CAPTURE option with preg_split
:
$s="test 18 119 19 50 20 #@$@#%";
echo implode('', preg_split('~\b(1[89]|20)\b|[^a-z\s] ~', $s, -1, PREG_SPLIT_DELIM_CAPTURE));