Backend Development 4 min read

PHP strchr() Function: Syntax, Parameters, Return Values, and Usage Examples

The article explains PHP's strchr() function, detailing its syntax, parameters, return values, and providing code examples for finding characters, substrings, retrieving text before a needle, and handling cases where the needle is absent.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP strchr() Function: Syntax, Parameters, Return Values, and Usage Examples

Function Overview

The strchr() function is a PHP string handling function that searches for a specified character or substring within a string and returns that character (or substring) together with the rest of the string.

Syntax

<code>string strchr ( string $haystack , mixed $needle [, bool $before_needle = false ] )</code>

Parameter Description

$haystack : The string to be searched.

$needle : The character or substring to look for.

$before_needle (optional): When set to true, the function returns the part of the string before the found character or substring.

Return Value

If the specified character or substring is found, the function returns that character (or substring) and everything that follows it; otherwise it returns false .

Detailed Usage

Finding a character

Example of locating the character 'W' in a string:

<code>$str = "Hello World";
$char = strchr($str, 'W');
echo $char; // outputs: World</code>

Finding a substring

Example of locating the substring "World":

<code>$str = "Hello World";
$subStr = strchr($str, 'World');
echo $subStr; // outputs: World</code>

Getting the part before the needle

Set $before_needle to true to retrieve the portion before the found character:

<code>$str = "Hello World";
$before = strchr($str, 'W', true);
echo $before; // outputs: Hello </code>

Handling a missing needle

If the needle is not present, the function returns false , which can be checked with a conditional statement:

<code>$str = "Hello World";
$char = strchr($str, 'Z');
if ($char === false) {
    echo "Character not found";
} else {
    echo $char;
}</code>

Summary

The strchr() function is a versatile PHP tool for searching strings, capable of returning the found portion, the substring before it, or indicating failure, making it useful for various string manipulation tasks.

backend-developmentPHPcode examplesstring-functionsstrchr
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.