Backend Development 4 min read

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:

<code><?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>";
}
?>
</code>

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:

<code><?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>";
}
?>
</code>

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

backend developmentPHPstring-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

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.