1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Need help with preg_match

Discussion in 'PHP' started by Christian Little, Mar 29, 2010.

  1. #1
    I suck at regex and really need some help here.

    I built the following function:

    
    function foundit($kw, $words) {
    
    	foreach($words as $word) {
    		$word = rtrim($word);
    		$match = 0;
    		if(preg_match("/$kw/i", $word)) { $match = 1; break; }
    	}
    		return($match);
    }
    
    PHP:
    What it's supposed to do is take in a specific word ($kw), as well as an array of keywords ($words). It's supposed to go through every word in $words to see if there's a regex match against $kw. If it finds a match anywhere, the function will return 1, otherwise it will return 0.

    Example 1:

    if(foundit("test", array("t1", "moo", "test", "test word"))) {do something...}
    PHP:
    This will return 1 because "test" is in the list of words.

    Example 2:

    if(foundit("test word", array("t1", "moo", "test", "test word"))) {do something...}
    PHP:
    This will return 0, and it's where I'm having the problem. It's having issues with the space and I'm not sure how to deal with that.

    So can somebody tell me what I need to do to the regex to make it work for example 2 please?


    Alternatively, if somebody could provide me with a better way of doing this I would be greatful. Basically I need a way to take a specific keyword and do a regex match against a list of keywords. But it needs to do partial matches too (i.e. if the word I'm looking for is "test", it should match even if the only word in the list is "some test" as test is in that phrase).

    Thanks very much for the help :)
     
    Christian Little, Mar 29, 2010 IP
  2. Narrator

    Narrator Active Member

    Messages:
    392
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    80
    #2
    The code worked fine for me I got 1's for both. What version of php are you running?

    try escaping the space with \s
     
    Narrator, Mar 29, 2010 IP