Difference between strstr and stristr in php


strstr() and stristr both are used to find the first occurence of the string.

stristr( ) is case insensitive and strstr( ) is case sensitive.


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

haystack
The input string.
needle
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
before_needle
If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle). By default it is FALSE.

strstr() – Find first occurrence of a string

Syntax:
strstr ($string, string)

Example:


<?php
$email = 'siddharth@yaHoo.com';
$domain_name = strstr($email, 'H');
echo $domain_name;
?>

Output:Hoo.com

stristr() – Find first occurrence of a string (Case-insensitive)

Syntax:
stristr ($string, string)

Example:


<?php
$email = 'siddharth@yaHoo.com';
$domain_name = stristr($email, 'H');
echo $domain_name;
?>

Output: harth@yaHoo.com

If we want to return the string before the haystack then we need to write the code as:


<?php
$email = 'siddharth@yaHoo.com';
$domain_name = stristr($email, 'H', TRUE);
echo $domain_name;
?>

Output: sidd
Advertisements

One thought on “Difference between strstr and stristr in php

Leave a Reply

Please log in using one of these methods to post your comment:

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 )

Connecting to %s