2

Why does this code not echo 0?

$email = "test@example.com";
$ending = "com";

$email = preg_replace('/[^A-Za-z0-9\-]/', '', $email);

echo substr_compare($email, $ending, strlen($ending)-strlen($email), strlen($ending));

I am expecting 0, per documentation.

Dummy Code
  • 1,858
  • 4
  • 19
  • 38
  • 3
    `strlen($ending)-strlen($email)` Write that down with your example and put in the real numbers and do the math and see what offset you get and where you start the comparison. – Rizier123 Jun 24 '16 at 15:05
  • 1
    @Rizier123 D'oh! `-11`, I guess I need to just do `-strlen($ending)` – Dummy Code Jun 24 '16 at 15:07
  • 1
    Sometimes when you have a small code example it helps when you write it down and put in the real numbers/values. – Rizier123 Jun 24 '16 at 15:08
  • @num8er It might be similar, since it shows another way to do it, but I think OP asks here why he got not 0 as output in his specific example. – Rizier123 Jun 24 '16 at 15:15
  • @Rizier123 author wants to compare that it ends with "com". See title: "Substring Compare PHP". And wants to debug the result by doing echo. I thing var_dump() will return expected result. – num8er Jun 24 '16 at 15:15
  • @Rizier123 Does that mean this answer is wrong? http://stackoverflow.com/a/619725/2379592 – Dummy Code Jun 24 '16 at 16:36

1 Answers1

0

If You want to check if it ends with "com".

Read this: startsWith() and endsWith() functions in PHP


But if You just want to debug the result:

Try to convert integer to string to properly output result.

echo (string)substr_compare($email, $ending, strlen($ending)-strlen($email), strlen($ending));

or do:

$result = substr_compare($email, $ending, strlen($ending)-strlen($email), strlen($ending));
var_dump($result); // or echo (string)$result;
Community
  • 1
  • 1
num8er
  • 18,604
  • 3
  • 43
  • 57