Please Help With Regular Expression

Discussion in 'Programming' started by deriklogov, Feb 4, 2013.

  1. #1
    I have this string

    "I love townhouses and townhomes"

    how to check with regular expression if townhouses and townhomes are present in that string ??
    I try to use this pattern:

    (townhouse|townhome)

    but it works as townhouse OR townhome ,
    how to make it search townhouse AND townhome ?
     
    Solved! View solution.
    deriklogov, Feb 4, 2013 IP
  2. #2
    You should be able to do something like this. Will be true if the sentence contains both words, false if not/

    $sentence = 'I love townhouses and townhomes';
    $exists = preg_match('/^(?=.*\btownhomes)(?=.*\btownhouses)/', $sentence, $res) && isset($res[0]);
    PHP:
    edit: I realise the question was non-language specific, so the following pattern should answer your original question:

    ^(?=.*\btownhomes)(?=.*\btownhouses)
    Code (markup):
     
    Last edited: Feb 4, 2013
    Alex Roxon, Feb 4, 2013 IP
    deriklogov likes this.