php – Differences between strpos, strstr and preg_match

Question:

PHP offers numerous methods to find out if a text string contains another substring:

  • strpos : to find the first occurrence
  • strrpos : to find the last occurrence
  • strstr : to find the first occurrence
  • preg_match : to search using (or not) with regular expressions

What are the differences between them (especially strpos and strstr )? Is there one that is faster? Which of them is more recommended or does it depend on the situation?

Answer:

As far as functionality is concerned, it would depend on what you want to find.

For example, we are going to find the element "world" within this string (you can check that I have put the word world within the string twice):

$string = "jersiojresoiresmundojrepiojreopsijreposijmundorpeosijreoisj";

And we are going to apply the different methods, which seem similar, but are not the same:

strpos

echo strpos($string, "mundo"); //Devuelve 15, la POSICIÓN de la primera ocurrencia

strrpos

echo strrpos($string, "mundo"); //Devuelve 41, la POSICIÓN de la última ocurrencia.

strstr

echo strstr($string, "mundo"); //Devuelve "mundojrepiojreopsijreposijmundorpeosijreoisj", es decir, todo el String desde la primera ocurrencia

preg_match

echo preg_match("/mundo/i", $string); //Devuelve 1 ya que ha encontrado la cadena dentro del string. En caso contrario, marcaría un 0

echo preg_match("/casa/i", $string); //Devuelve 0

As for whether strpos or strstr is faster, as indicated by the PHP documentation for the case of strstr :

If you only want to know if a certain needle appears in a haystack, use the strpos () function which is faster and requires less memory.

Scroll to Top