PHP string based question

Question : Find number in a string?

preg_replace(“/[^0-9]/”,””,$string); Return string
filter_var($str, FILTER_SANITIZE_NUMBER_INT);
preg_match_all(‘!\d+!’, $str, $matches); Return an array

strpos() : Find the postion in string
Example : echo strpos(“I love php, I love php too!”,”php”);
Output: 7

strpos() : Finds the position of the first occurrence of a string inside another string (case-sensitive)

stripos() : Finds the position of the first occurrence of a string inside another string (case-insensitive)

strripos() : Finds the position of the last occurrence of a string inside another string (case-insensitive)\

substr : Return “world” from the string
Example : echo substr(“Hello world”,-1);
Output : d

strrev() : Reverse the string

strrev(“Hello World!”) : !dlroW olleH

 

Question: Output of code :

$str1 = 'yabadabadoo';
$str2 = 'yaba';
echo  $haspostion = strpos($str1,$str2)) {     ;

Output : 0

Explanation : it show 1st occurence of “yaba” in string which is on position 0 show output will be 0. To awoid this problem we have to check it with

if(strpos($str1, $str2) !== false){

//….you code is here

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s