Home php How to check if a string contains a substring

How to check if a string contains a substring

Author

Date

Category

Hello, there is a variable $ message = 'Like message, parrot, seagull, 801';

How to check if a given variable contains a valid word parrot .


Answer 1, authority 100%

http://php.net/manual/en/function.strpos.php – returns the position of the first occurrence of a substring

Example from the documentation:

$ mystring = 'abc';
$ findme = 'a';
$ pos = strpos ($ mystring, $ findme);
// Note that === is used. Using == will fail
// result, since 'a' is at position zero.
if ($ pos === false) {
  echo "String '$ findme' was not found in string '$ mystring'";
} else {
  echo "String '$ findme' found in string '$ mystring'";
  echo "at position $ pos";
}

there is still http://php.net/manual/en/function.stripos .php – just like strpos, it returns the position of the first occurrence of a substring, but all this is case-insensitive. Again an example from the documentation:

$ findme = 'a';
$ mystring1 = 'xyz';
$ mystring2 = 'ABC';
$ pos1 = stripos ($ mystring1, $ findme);
$ pos2 = stripos ($ mystring2, $ findme);
// Of course, 'a' is not included in 'xyz'
if ($ pos1 === false) {
  echo "String '$ findme' was not found in string '$ mystring1'";
}
// Note that === is used. Using == will fail
// result, since 'a' is at position zero.
if ($ pos2! == false) {
  echo "Found '$ findme' in '$ mystring2' at position $ pos2";
}

As a post scriptum: I recommend that you familiarize yourself with all the functions for working with strings, or at least the basic ones. They are written here: http://php.net/manual/en/ref.strings .php

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions