Manipulating and Searching Strings
PHP has many functions to work with strings. The most commonly used
functions for searching and modifying strings are those that use regular
expressions to describe the string in question. The functions described in
this section do not use regular expressions—they are faster than regular
expressions, but they work only when you’re looking for a fixed string
(for instance, if you’re looking for "12/11/01" rather than “any numbers separated by
slashes”).
Substrings
If you know where the data that you are interested in lies
in a larger string, you can copy it out with the substr() function:
$piece=substr(string,start[,length]);
The start argument is the position in
string at which to begin copying, with
0 meaning the start of the string.
The length argument is the number of
characters to copy (the default is to copy until the end of the string).
For example:
$name="Fred Flintstone";$fluff=substr($name,6,4);// $fluff is "lint"$sound=substr($name,11);// $sound is "tone"
To learn how many times a smaller string occurs in a larger
one, use substr_count():
$number = substr_count(big_string,small_string);
For example:
$sketch=<<<EndOfSketchWell,there'seggandbacon;eggsausageandbacon;eggandspam;eggbaconandspam;eggbaconsausageandspam;spambaconsausageandspam;spameggspamspambaconandspam;spamsausagespamspambaconspamtomatoandspam;EndOfSketch;$count=substr_count($sketch,"spam");("The word spam occurs ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access