How can you capture and return the matched word in a string using regular expressions in PHP?
To capture and return the matched word in a string using regular expressions in PHP, you can use the `preg_match()` function. This function searches a string for a pattern and returns true if the pattern is found, and false otherwise. To capture the matched word, you can use parentheses `()` in the regular expression pattern to create a capturing group. The matched word can then be accessed using the `$matches` array.
$string = "The quick brown fox jumps over the lazy dog";
$pattern = '/\b(brown)\b/';
if (preg_match($pattern, $string, $matches)) {
echo "Matched word: " . $matches[1];
} else {
echo "No match found";
}
Keywords
Related Questions
- What best practices should be followed when handling database queries in PHP to ensure accurate and efficient results?
- In what ways can the PHP code be structured to handle the generation of a Sudoku puzzle more effectively and accurately?
- What are the potential risks of storing file paths in a MySQL database?