tags:

views:

51

answers:

2

i wrote a regex, but it doesn't work as i expect. Take a look please


preg_match_all("/([\.\:]?)(.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})/siu",$content,$matched);

[^\s]*".preg_quote($word)."[^\s]//

this part match the whole word, if it contain the keyword, for example it match keyword if i search for wor keyword.

.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65}

here i get up to 65 characters before and after the keyword, ie. i will get

many words here keyword and other words here


And now, what is the problem. I try to match the sentence from the begining, if there is any of [.:] characters within {65} characters

if i have sach structure - word1 word2 . {less then 65 character here} keyword {other characters here}

i expect, then if i wrote ([\.\:]?)(.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})

it will match .{less then 65 character here} keyword {65 characters}

but it doesn't. the part [\.\:]? hasn't any influence on regex. it match all {65} characters.

i need to match sentence from begining, if the start of sentence within 65 characters before the keyword

Thanks much

+1  A: 

Simply replace the fist

.{0,65}

by

[^\.\:]{0,65}

After all, It may be looked like

preg_match_all("/([^\.\:]{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})/siu",$content,$matched);
DQM
+1  A: 

[.:]? means "match a dot (.), a colon (:), or nothing"; if the next character is not a dot or colon, ([.:]?) matches nothing. Then .{0,65} matches up to 65 of anything, including . or :. I think this is what you're looking for:

$source='A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids.';
$word = 'regular';
preg_match_all('#[^.:]{0,65}\b'.preg_quote($word).'\b.{0,65}#siu', $source, $matches);
print_r($matches);

output:

Array
(
  [0] => Array
    (
      [0] => A regular expression (regex or regexp for short) is a special text string 
      [1] =>  You can think of regular expressions as wildcards on steroids.
    )

)

(See it live on Ideone)

Alan Moore
perfect. Thanks man:/
Syom