preg_match
<html><head><title>preg_match example with PHP</title></head>
<body>
<table summary='match results'>
<?php
function does_match($p, $t) {
print "<tr><td>$t</td><td>";
if (preg_match($p, $t)) {
print "matches";
}
else {
print "doesn't match";
}
print "</td><td>$p</td></tr>";
}
$pattern = '/foo/i';
$with_foo = 'I have a Foo.';
$no_foo = 'I do not.';
does_match($pattern, $with_foo);
does_match($pattern, $no_foo);
$pattern = '/\[in\]/';
$in_1 = 'does [in] match?';
$in_2 = 'does in match?';
$pattern = '/[in]/';
$in_1 = 'abcdefgh jklm opqrs uvwxyz';
$in_2 = 'abdef ghij lm opq stu wxyz';
does_match($pattern, $in_1);
does_match($pattern, $in_2);
$pattern = '/end$/';
$dollar_1= 'at the end';
$dollar_2= 'at the end NOT';
does_match($pattern, $dollar_1);
does_match($pattern, $dollar_2);
?>
</table>
<p>See also <a href='preg_replace.html'>preg_replace.html</a>.
</body><html>
preg_replace
In its most basic form, preg_replace
takes the following three parameters: preg_replace($pattern, $replacement, $text)
.
The two optional parameters are limit
and count
.
<html><head><title>preg_replace example with PHP</title></head>
<body>
<pre>
<?php
$pattern = '/foo/i';
$replace = 'bar';
$text = 'one foo and another FOO to be replaced';
print "pattern: " . $pattern . "<br>";
print "replace: " . $replace . "<br>";
print "text: " . $text . "<br>";
print "result: " . preg_replace($pattern, $replace, $text);
?>
</pre>
<h2>preg_replace with arrays</h2>
<code>
<?php
$text = 'one foo and another FOO to be replaced';
print "result: " . preg_replace(
array('/foo/i' ,'/ to be /'),
array( 'bar' , ' were ' ),
$text);
print "<p>";
$text = 'The word is: strawberry';
# Replace from left to right.
print "result: " . preg_replace(
array( '/strawberry/', '@lemon@', '!orange!'),
array( 'lemon' , 'orange', 'pear' ),
$text);
?>
</code>
<p>See also <a href='preg_match.html'>preg_match.html</a> and <a href='str_replace.html'>str_replace.html</a>.
</body><html>