-3

i try to check a string with strpos().

$a = $_SERVER['REQUEST_URI'];

This works just fine

if (strpos($a, 'en' ) == true)

But this doesn't

if (strpos($a, '/en/' ) == true) - Doesn't work

I tried a lot of things to escape the character or format the string but as it seems I am too stupid...

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
Lukas Hwm
  • 3
  • 1
  • 4

1 Answers1

5

The issue is that strpos returns the position or FALSE if not found.

So if the url is /en/something/some then you are hitting the situation where en is a position 1 and any non-zero number is true

When you do /en/ then the starting position is 0 and that is false.

you need to check with === in the end or more accurately !== example

<?php

$a= "/en/blo";

if (strpos($a, '/en/' ) !== false){
    echo "TRUE";
} else {
    echo "FALSE";
}
nerdlyist
  • 2,842
  • 2
  • 20
  • 32
  • 1
    That's it. Working perfectly. Can't tell you how thankful I am for your solution as also for the explanation. – Lukas Hwm Jan 25 '18 at 14:34
  • How about url like this `/jp/home/en/content`, it will TRUE also.. – Mochamad Arifin Jan 25 '18 at 14:53
  • @MochamadArifin yeah he is just looking for `\en\` as far as I can tell. The only issue is when it is at the beginning cause 0 = false. If you want to check the first 4 are `/en/` I would just substr and verify or just straight up make sure strpos for `/en/` is 0. – nerdlyist Jan 25 '18 at 17:36
  • @LukasHwm glad to help. Not sure if you can but accepting the answer is always appreciated! – nerdlyist Jan 25 '18 at 17:37