Regex should be used for other uses besides getting strings out of strings or otherwise cutting strings into pieces.
Parsing string using regular expressions
preg_match can be used to parse string using regular expression. The parts of expression enclosed in parenthesis are called subpatterns and with them you can pick individual parts of the string.
Searching a substring with strpos
strpos can be understood as the number of bytes in the haystack before the first occurrence of the needle.
Checking if a substring exists
Be careful with checking against TRUE or FALSE because if a index of 0 is returned an if statement will see this as FALSE.
Output of the whole example:
Search starting from an offset
Get all occurrences of a substring
Splitting a string by separators
strstr are simpler methods to get substrings by separators.
A string containing several parts of text that are separated by a common character can be split into parts with the
The method also supports a limit parameter that can be used as follow:
If the limit parameter is zero, then this is treated as 1.
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
If the limit parameter is negative, all components except the last -limit are returned.
explode can be combined with
list to parse a string into variables in one line:
However, make sure that the result of
explode contains enough elements, or an undefined index warning would be triggered.
strstr strips away or only returns the substring before the first occurrence of the given needle.
Substring returns the portion of string specified by the start and length parameters.
If there is a possibility of meeting multi-byte character strings, then it would be safer to use mb_substr.
Another variant is the substr_replace function, which replaces text within a portion of a string.
Let's say you want to find a specific word in a string - and don't want to use Regex.
Another option is a very basic parsing of an email.
Or even putting the "Continue reading" or "..." at the end of a blurb
This modified text is an extract of the original Stack Overflow Documentation created by following contributors
and released under CC BY-SA 3.0