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

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

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:

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

Finding a substring

Example of locating the substring "World":

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

Getting the part before the needle

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

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

Handling a missing needle

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

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

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend-developmentPHPCode Examplesstrchr
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

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.