Using strpos() and strrpos() Functions to Detect Substrings in PHP

These PHP tutorials demonstrate how to use the strpos() and strrpos() functions to detect the presence and position of characters in strings, explaining return values, providing complete code examples, and offering additional learning resources for backend development.

php Courses
php Courses
php Courses
Using strpos() and strrpos() Functions to Detect Substrings in PHP

Method 1: Detect using strpos() function

strpos()

function can find the position of the first occurrence of a substring within another string (case-sensitive).

If the specified character exists, it returns the position of the first occurrence; otherwise it returns FALSE.

Note: String positions start at 0, not 1.

Example:

<?php
header('content-type:text/html;charset=utf-8');   
$findme = 'C';
$mystring1 = 'xyz';
$mystring2 = 'ABC';
$pos1 = strpos($mystring1, $findme);
$pos2 = strpos($mystring2, $findme);
var_dump($pos1);
var_dump($pos2);
if($pos1){
 echo $mystring1." 中指定字符 C<br>";
}else{
 echo $mystring1." 中不包含指定字符 C<br>";
}
if($pos2){
 echo $mystring2." 指定字符 C<br>";
}else{
 echo $mystring2." 不包含指定字符 C<br>";
}
?>

Method 2: Detect using strrpos() function

strrpos()

function can find the position of the last occurrence of a substring within another string (case-sensitive).

If the specified character exists, it returns the position of the last occurrence; otherwise it returns FALSE.

Example:

<?php
header('content-type:text/html;charset=utf-8');   
$findme = 'c';
$mystring1 = 'xyzc';
$mystring2 = 'ABC';
$pos1 = strrpos($mystring1, $findme);
$pos2 = strrpos($mystring2, $findme);
var_dump($pos1);
var_dump($pos2);
if($pos1){
 echo $mystring1." 中指定字符 c<br>";
}else{
 echo $mystring1." 中不包含指定字符 c<br>";
}
if($pos2){
 echo $mystring2." 指定字符 c<br>";
}else{
 echo $mystring2." 不包含指定字符 c<br>";
}
?>

PHP Learning Recommendations

Vue3+Laravel8+Uniapp Beginner to Practical Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole from Beginner to Mastery – Recommended Course

Workerman+TP6 Instant Messaging Chat System – Limited‑time Offer

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.

PHPString Functionsstrrposstrpos
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.