strchr() – PHP String Functions

Syntax :

strchr ( string, search, before_search );

Description :

strchr() function will find the first occurrence of search in a string. This function is an alias of the strstr() function.

Note : This function is binary-safe.
Note : This function is case-sensitive. For a case-insensitive search, use stristr() function.

Parameter :

  • string – This is a Required parameter. This is the string which is to be searched.
  • search – This is a Required parameter. It contains the value to be seacrhed. If we pass this parameter as a number, then it will search for the character matching the ASCII value of the number.
  • before_search –  This is an Optional parameter. A Boolean value, default is set to “false”.  If set to “true”, it returns the part of the string before the first occurrence of the search parameter.

Output :

It will returns below values:

  • the portion of string after the first occurrence is found in the string
  • FALSE if the search is not found in the string.

ChangeLog :

[table caption=”” width=”100%” colwidth=”25%|75%” colalign=”left|left”]
Version, Description
PHP 5.3 , The before_search parameter was added.
PHP 4.3.0, strchr() was made binary safe function.

[/table]


Related articles :  strstr()stristr(), strpos()strrchr() strpbrk().


strchr() – PHP Functions Example 1 : It returns the string from the first occurrence of search is found.
<?php
echo strchr("Hi from tutorialmines.","from"); // case-sensitive comparison
?>

Output of above code in the browser is as below:

from tutorialmines.

strchr() – PHP Functions Example 2 : It will find the first occurrence of character “f”, its ASCII value is 102.
<?php
echo strchr("Hi from tutorialmines.",102);// ASCII value of f is 102.
?>

Output of above code in the browser is as below:

from tutorialmines.

strchr() – PHP Functions Example 3 : Using before_search parameter.
<?php
echo "Using before_search 3rd parameter in the function<br />";
echo strchr("Hi from tutorialmines.","tutorialmines",true); // case-sensitive comparison
echo "<br/>";
echo strchr("Hi from tutorialmines.",116,true);// ASCII value of t is 116.
?>

Output of above code in the browser is as below:

Using before_search 3rd parameter in the function
Hi from
Hi from

strchr() – PHP Functions Example 4 : It will return FALSE, if string is not found in the search.
<?php
echo "returns false, if search string is not found.<br />";
var_dump(strchr("Hi from tutorialmines.","the"));// returns false, if search string is not found.
echo "<br/>";
var_dump(strchr("Hi from tutorialmines.","me",true)); // case-sensitive comparison
echo "<br/>";
var_dump(strchr("Hi from tutorialmines.",098,true));// ASCII value of bt is 098.
?>

Output of above code in the browser is as below:

returns false, if search string is not found.
bool(false)
bool(false)
bool(false)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *