Examples of commonly used string lookup functions strstr() and strpos() in php

 

 string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

1. $haystack is the searched string, $needle is the content to be searched
2. If found, return part of the string, if not found, return FALSE
3. This function is case-sensitive, if you want to be case-insensitive, Please use strpos()
4. If you just want to determine if the needle exists in the haystack, please use the strpos() function which is faster and consumes less memory

<?php
	$email = '[email protected]';
	$domain = strstr($email,'@');
	$name = strstr($email,'@',TRUE);
	$no_con = strstr($email,'99');

	echo $domain; //output @example.com
	echo $name; // output name from PHP 5.3.0
	var_dump($no_con); //If not found, return boolean FALSE
?>

 mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

1. The string to be searched for in $haystack, the content to be found in $needle
2. Returns the first number position of the needle in haystack
3. The function is case-sensitive. If you want to be case-insensitive, please use stripos()
4 , return value, if found, return the needle exists in the starting position of the haystack string (note that the string position starts from 0, not from 1), if not found, it returns FALSE, but it may also return equivalent to FALSE non-boolean

<?php
	$mystring  =  'abc' ;
 	$findme    =  'a' ;
 	$pos = strpos($mystring,$findme);
 	echo $pos; //Output 0, which is the current position of a
?>

 Here are two similar functions, which are briefly introduced here, just remember to have this function, and simply read the manual when using it.

1. strrpos(), calculate the position of the last occurrence of the specified string in the target string
2. strripos(), calculate the position of the last occurrence of the specified string in the target string (case-insensitive)

Summary: Note that if these functions are not found, they will return FALSE, so when judging whether the two sides are equal (if), pay attention to the types of both sides. The above functions are the most commonly used string search functions in PHP. If more powerful functions are needed, such as matching and verification of email addresses and mobile phone numbers, regular expressions are required.

The original text is reproduced from: // Jin Sanguo

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326746767&siteId=291194637