2

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.

Laberkopf
  • 75
  • 1
  • 10

1 Answers1

1

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

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Ok, thats right, but if I exchange the "x" to a "d", because the "x" in the example in reality was an "d" (the same in the strings, for an example "77-546-00X" is in reality "77-546-00D" ) and if I replace that in my Code, so the Answer is not right, can you help me? Here can you see what I min: https://3v4l.org/m1Fin – Laberkopf Nov 20 '18 at 08:56
  • In what way is the answer not right? It is listing all the values that end in a `d`... – Nick Nov 20 '18 at 11:23
  • Yes, that is right, but I only need the strings, which only contains "D" not "DA", "XD", "YD" or somethingelse, only which has the letter "D" at the end, that is very important. ;-) – Laberkopf Nov 20 '18 at 14:52
  • @Laberkopf I have modified my answer and demo. I think that should do what you want. – Nick Nov 20 '18 at 22:16