Image for Php Regex

Find whole line that contains word with php regular expressions

You want to search for a word “vikram” in a text along with the whole line in which this word appears, no worry following is the solution ;). We would be using php regular expressions for this.

A simpler pattern would be ‘/^.*\bvikram\b.*$/m’

Explanation for regex :

That is, from the start of a line (^) match 0 or more of any character (.*), a word-boundary (\b), the word “vikram”, another word boundary, another series of characters, and the end of the line ($), matching over multiple lines (m modifier).

Here’s a proof-of-concept, finding the entire middle line which contains the word:

Code :


<?php

$lines ="This is a test
for finding the word vikram in a
bunch of lines of text";

$pattern = "/^.*\bvikram\b.*$/m";

$matches = array();
preg_match($pattern, $lines, $matches);

var_dump($matches);

?>

Output :


array(1) {
[0]=>
string(33) "for finding the word vikram in a "
}

Vikram Pawar

Vikram Pawar

Coder by passion..... Thirsty for knowledge, challenges & most importantly innovation. Working with BNP Paribas

Leave a Reply

Your email address will not be published. Required fields are marked *