PHP strchr() Function (original) (raw)

Last Updated : 21 Jun, 2023

The strchr() function is a built-in function in PHP and is used to search for the first occurrence of a given string(say searchStr) in another string(say originalStr) and returns the rest of the string from originalStr starting from the first occurrence of searchStr in orignalStr.

Note: The strchr() function is case sensitive.

Syntax:

strchr($originalStr, searchStr,searchStr, searchStr,before_search

Parameter:

Return Value: It returns a string depending on the below three cases:

Examples:

Input : $originalStr = "geeks for geeks" $searchStr = "geeks" Output : geeks for geeks

Input : $originalStr = "geeks for geeks" $searchStr = "for" Output : for geeks

Input : $originalStr = "striver has published 180 articles" searchStr="has"searchStr = "has" searchStr="has"before_search = TRUE Output : striver

Input: originalStr="geeksforgeeks"originalStr = "geeks for geeks" originalStr="geeksforgeeks"searchStr = "gfg" Output: No output

Below programs illustrate the strchr() function in PHP:

Program 1: Program to demonstrate strchr() function when word is found.

PHP

<?php

$originalStr = "geeks for geeks" ;

$searchStr = "geeks" ;

echo strchr ( $originalStr , $searchStr );

?>

Output:

geeks for geeks

Program 2: Program to demonstrate strchr() function when word is not found.

PHP

<?php

$originalStr = "geeks for geeks" ;

$searchStr = "gfg" ;

echo strchr ( $originalStr , $searchStr );

?>

Output:

No Output

Program 3: Program to demonstrate strchr() function when word is found and $before_search is set to true.

PHP

<?php

$originalStr = "geeks for geeks" ;

$searchStr = "for" ;

echo strchr ( $originalStr , $searchStr , true);

?>

Output:

geeks

Program 4: Program to demonstrate strchr() function when a part of word is passed and found.

PHP

<?php

$originalStr = "geeks for geeks" ;

$searchStr = "eks" ;

echo strchr ( $originalStr , $searchStr );

?>

Output:

eks for geeks

Program 5: Program to demonstrate strchr() function when a number is passed and its equivalent ASCII character is searched.

PHP

<?php

$originalStr = "geeks for geeks" ;

$searchStr = 101 ;

echo strchr ( $originalStr , $searchStr );

?>

Output:

eeks for geeks

Reference:
http://php.net/manual/en/function.strchr.php