Common PHP String Manipulation Functions and Examples
This article explains several essential PHP string functions—including substr, mb_substr, stripos with substr, and direct character indexing—providing clear code examples and output demonstrations for handling both ASCII and multibyte characters.
PHP string functions are a core part of the language, and this guide covers the most commonly used methods for extracting substrings.
1. substr() extracts a portion of a string based on start position and length.
<?php
$str = "laravel";
echo substr($str,3); // avel
echo "<br/>";
echo substr($str,2,4); // rave
echo "<br/>";
echo substr($str,-3); // vel
?>The outputs are avel, rave, and vel respectively.
2. mb_substr() handles multibyte characters such as Chinese, requiring the php_mbstring extension.
<?php
echo mb_substr("文字内容",2,1,"UTF-8"); // 内
?>Output: 内.
To obtain the part of a string before a certain number of characters, calculate the total length and subtract the desired offset:
<?php
$weishu = 3;
echo mb_substr("文字内容", 0, mb_strlen("文字内容", 'utf8') - $weishu); // 文
?>Result: 文.
3. Using stripos() with substr() to locate a character and extract substrings to the left or right of it.
<?php
echo substr("abcde", stripos("abcde", "c")); // cde
echo "<br/>";
echo substr("abcde", 0, stripos("abcde", "c")); // ab
?>Outputs are cde and ab.
4. Direct character access by index using array syntax.
<?php
$str = "laravel";
echo $str[3]; // a
?>Output: a.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
