I have an array (converted from a string) that contains words with non-standard letters (letters not used in English, like ć, ä, ü). I don’t want to replace those characters, I want to get rid of the whole words that have them.
from [Adam-Smith, Christine, Müller, Roger, Hauptstraße, X Æ A-12]
to [Adam-Smith, Christine, Roger]
This is what I got so far:
<?php
$tags = "Adam-Smith, Christine, Müller, Roger, Hauptstraße, X Æ A-12";
$tags_array = preg_split("/,/", $tags);
$tags_array = array_filter($tags_array, function($value){
return strstr($value, "a") === false;
});
foreach($tags_array as $tag) {
echo "<p>".$tag."</p>";
}
?>
I have no idea how to delete words that are not [a-z, A-Z, 0-9] and [(), "", -, +, &, %, @, #] characters. Right now the code deletes every word with an "a". What should I do to achieve this?
3
Answers
This should do the work for you
https://onlinephp.io/c/dd46c
output
Yields:
If you want to include a full stop as an allowable character (if you were checking for email addresses), you can add
.
to the end of the regex.This task can be completed more directly/efficiently than the earlier answers demonstrate. Just split on commas which may have leading or trailing spaces AND treat any names with non-whitelisted characters as delimiters too.
The result array will only contain the qualifying names and they will be whitespace trimmed without making any extra calls.
Code: (Demo)