Searching Strings
Problem
You want to search a string for a particular pattern or substring.
Solution
Use a regular expression with PHP’s ereg() function:
<?php
// define string
$html = “I’m <b>tired</b> and so I <b>must</b> go
<a href=’http://domain’>home</a> now”;
// check for match
// result: “Match”
echo ereg(“<b>(.*)+</b>”, $html) ? “Match” : “No match”;
?>
Use a regular expression with PHP’s preg_match() function:
<?php
// define string
$html = “I’m <b>tired</b> and so I <b>must</b> go
<a href=’http://domain’>home</a> now”;
// check for match
// result: “Match”
echo preg_match(“/<b>(.*?)<\/b>/i”, $html) ? “Match” : “No match”;
?>
Comments
When it comes to searching for matches within a string, PHP offers the ereg()
and preg_match() functions, which are equivalent: both functions accept a regular
expression and a string, and return true if the string contains one or more matches
to the regular expression. Readers familiar with Perl will usually prefer the preg_
match() function, as it enables them to use Perl-compliant regular expressions and,
in some cases, is faster than the ereg() function.