Check the start value of a variable

Asked

Viewed 67 times

0

I want to check if the initial value of a variable is "such". How can I do this? Follow an example for better understanding:

<?php

$teste = "(51) 3212-3212";

if ($teste =="(51)%") {
    echo "DEU CERTO!";
}

else {
    echo "DEU RUIM!";
}
?>
  • you want to just take the ddd and compare?

  • Oops. This. I want to know if the beginning of the variable corresponds to such value, through this, prints on the screen information. As in the example I put, the value of the $test variable is (51) 3212-3212, so I want when this variable starts with (51), no matter what comes after that (51), an information is displayed on the screen. Got it?

  • 2

    Uses PHP subster: http://php.net/manual/en/function.substr.php.

  • Excellent worked out friend. Thank you

  • If the answer was useful to you, you do not need to add the question to the solution, just accept the answer. How and why to accept an answer?

  • Another way would be using regular expression http://php.net/manual/en/function.preg-match.php

  • https://regex101.com/r/e6rmen/1

Show 2 more comments

1 answer

2

You can use the function strpos. She will return you to the position in which determined string was found in your variable $teste. Return 0, means that this string is at the beginning.

$teste = 'minha string';

if (strpos($teste, 'minha') === 0) {
      echo "'minha' está no início";
}

Translating the PHP documentation:

int strpos ( string $palheiro , string $agulha [, int $posição ] )

Returns the numerical position of the first occurrence of $agulha inside $palheiro.

  • 1

    Thanks for the answer. Thanks this way fell well into something else I will do.

  • @Carlos if solved the problem, please consider marking the answer that helped you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.