Sep

5

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!: &amp;nbsp;'". $str . "'</b><br/>";
    } else {
        print "<b>Didn't find it: &amp;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

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links