-2

I have a simple regex code to match a whole line in text file that has a specific word. I use PHP function preg_match_all.

this is my regex pattern:

$word= 'world';
$contents = '
this is my WoRld
this is my world
this is my wORLD
this is my home
';
$pattern = "/^.*$word.*\$/m";
preg_match_all($pattern, $contents, $matches);

// results will be in $matches[0]

this function get the full line but search for case sensitive only so it will return the second line only of the text.

I want it to match all line (that has "world" word in any form).

I read about using /i but I don't know how to combine it with the pattern above.

I tried:

/^.$pattern.\$/m/i

/^.$pattern.\$/m/i

/^.$pattern.\$/i

max max
  • 55
  • 7

1 Answers1

1

This expression,

(?i)^.*\bworld\b.*$

might simply return those desired strings.

Test

$re = '/(?i)^.*\bworld\b.*$/m';
$str = 'this is my WoRld
this is my world
this is my wORLD
this is my home';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

Output

array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(16) "this is my WoRld"
  }
  [1]=>
  array(1) {
    [0]=>
    string(16) "this is my world"
  }
  [2]=>
  array(1) {
    [0]=>
    string(16) "this is my wORLD"
  }
}

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    hello emma and than you for reply! the code work just fine but I don't know know why it takes more time than the old one :/ can you please tell me what to change in the regex code you provide to match world( OR wOrld ( OR worlD str123 ( .. I mean to match the word with parenthesis after even if there's anything between the word and the parenthesis .. Thank you in advance! – max max Sep 22 '19 at 20:39
  • 1
    thank you for reply! I was meaning to match the lines only with: world( OR wOrld ( OR worlD str123 ( in the string with the same new line condition like the original question :) – max max Sep 22 '19 at 20:54