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 in a larger string the interesting data lies, 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 = <<< End_of_Sketch Well, there's egg and bacon; egg sausage and bacon; egg and spam; egg bacon and spam; egg bacon sausage and spam; spam bacon sausage and spam; spam egg spam spam bacon and spam; spam sausage spam spam bacon spam tomato and spam; End_of_Sketch; $count = substr_count($sketch, "spam"); print("The word spam ...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