Monday, February 18, 2019

php - How I can check if a string contais "x" but not "xy"




How can I check if a string contains "x" but not "xy"?



So I have strings like this:



"5103564-XY",
"77-546-00X",
"292196232",
"5102200X",
"5102205",

"5102251-EP".
...


I only need the numbers which have the letter "x" at the end. Can Someone help me to realize that in PHP?



So if I try this:



$strings = array("5103564-AD", "77-546-00D", "292196232", "5102200D", "5102205", "5102251-EP");
print_r(preg_grep('/d$/i', $strings));



So the output is this:



Array
(
[0] => 5103564-AD
[1] => 77-546-00D
[3] => 5102200D
)



But this is not the wished result. I Only need the strings, which contains only the letter "D" and not the strings, which contains "AD" or somethingelse too. I hope it is now a little bit clearer, what I need/mine.


Answer



Use preg_grep to find only values in the list which end in just a d or D (with no preceding letter):



$strings = array("5103564-AD", "77-546-00D", "292196232", "5102200D", "5102205", "5102251-EP");
print_r(preg_grep('/[^a-z]d$/i', $strings));



Output:



Array ( 
[1] => 77-546-00D
[3] => 5102200D
)


Demo on 3v4l.org


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...