</head>
<body>
2) Create a string, search for a word in that string. If the word is found display word found. If not found display a message saying word not found.<br />
<?php
$subject = "I learn web development ";
$pattern = '/web/'; // I have also tried /^web$/ and /^web/
preg_match($pattern, $subject, $matches);
echo $matches[0];
?></body>
</html
ss
When I use this code, I am getting output as follows
2) Create a string, search for a word in that string. If the word is found display word found. If not found display a message saying word not found.
Array
Please suggest whats wrong and why am I not getting output as "web"
Works fine for me. You don't by any chance actually have a 4th parameter in your call to preg_match(), do you, as that would change the structure of the $matches array. You could try something like this to get some more info:
PHP Code:
<html>
<head>
</head>
<body>
2) Create a string, search for a word in that string. If the word is found display word found. If not found display a message saying word not found.<br />
<?php
$subject = "I learn web development ";
$pattern = '/web/'; // I have also tried /^web$/ and /^web/
if(preg_match($pattern, $subject, $matches)) {
if( ! is_string($matches[0])) {
echo "<pre>DEBUG\n".var_export($matches,true)."</pre>\n";
}
else {
echo $matches[0];
}
}
else {
echo "[not found]";
}
?></body>
</html>
PS: For something like this where you do not need the power of regular expressions, strpos() or stripos() along with substr() would probably be more efficient.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
</head>
<body>
2) Create a string, search for a word in that string. If the word is found display word found. If not found display a message saying word not found.<br />
<?php
$subject = "I learn web development "; $pattern = '/^web$/';
preg_match($pattern, $subject, $matches);
echo $matches[0];
?></body>
</html >
It does non work with this regex
I am getting following output
Notice: Undefined offset: 0 in C:\wamp\www\PHP_Assignment_3_StringAssignments.php on line 23
'/^web/' matches web only at the beginning of the string,
'/web$/' matches web only at the end of the string.
Then '/^web$/' matches only web in 'web' string !
I see.
I want to match only web word in entire string. If I make pattern as /web/, then it will match web anywhere in the string like webdevelopment, spiderweb etc. But I want only web word, mentioned separately in the entire string to be matched. How to do that ?
"\b" is "word boundary"
"i" after the closing delimiter is case-insensitive modifier
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks