Sep
5
PHP Regex - Search for Line Begins with a Word
September 5, 2008 |
This article teaches you how to use PHP regular expression to find whole words at the beginning of a line.
<html>
<head><title>Searching for lines beginning with a word</title></head>
<body>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="str"
value="<?php print $_POST['str'];?>" /><br />
<input type="submit" value="Find lines" /><br /><br />
<?php
if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
$str = $_POST['str'];
if ( preg_match( "/^Word\b/", $str ) )
{
print "<b>Found a match!: &nbsp;'". $str . "'</b><br/>";
} else {
print "<b>Didn't find it: &nbsp;'". $str . "'</b><br/>";
}
}
?>
</form>
</body>
</html>
Regular Expression Explanation:
|
^ |
at the start of the line, followed immediately by … |
|
W |
then … |
|
o |
followed by … |
|
r |
then … |
|
d |
and lastly … |
|
\b |
a word boundary. |
Similar Posts
- PHP Regex - Search for Line Ends with a Word
- PHP Regular Expression - Search for Words Within Comments


































