I am looking for an alternative to preg_match. preg_match returns true or false the the regex was found. I am looking for something that returns the string if it is found. I tried using preg_grep with no luck, it's always returning the entire line. Eg. $strSearch = "We went to the store."; if($strMatch = preg_match("/[a-zA-Z0-9]+ore/", $strSearch)) { echo $strMatch; } //This should return 'store', instead of true PHP:
Actually, preg_match returns an integer; you're just interpreting the return value as boolean. Include the $matches parameter to accomplish what you desire and read up on preg_match and preg_match_al. <?php $strSearch = "We went to the store with the intention of buying something from the store. " ."When we got to the store, we discovered the store was closed. " ."So we returned home with nothing to store in cupboard."; if($strMatch = preg_match("/[a-zA-Z0-9]+ore/", $strSearch, $matches)) { echo '<pre>'; print "Matches: $strMatch<br>"; print_r($matches); echo '</pre>'; } /* Outputs: Matches: 1 Array ( [0] => store ) */ if($strMatch = preg_match("/[a-zA-Z0-9]+ore/", $strSearch, $matches, PREG_OFFSET_CAPTURE)) { echo '<pre>'; print "Matches: $strMatch<br>"; print_r($matches); echo '</pre>'; } /* Outputs: Matches: 1 Array ( [0] => Array ( [0] => store [1] => 15 ) ) */ if($strMatch = preg_match_all("/[a-zA-Z0-9]+ore/", $strSearch, $matches, PREG_OFFSET_CAPTURE)) { echo '<pre>'; print "Matches: $strMatch<br>"; print_r($matches); echo '</pre>'; } /* Outputs: Matches: 5 Array ( [0] => Array ( [0] => Array ( [0] => store [1] => 15 ) [1] => Array ( [0] => store [1] => 69 ) [2] => Array ( [0] => store [1] => 95 ) [3] => Array ( [0] => store [1] => 120 ) [4] => Array ( [0] => store [1] => 174 ) ) ) */ ?> Code (markup):
Like dgreenhouse said, the matches will be stored in the third parameter you pass through. i.e. using your code: $strSearch = "We went to the store."; if($strMatch = preg_match("/[a-zA-Z0-9]+ore/", $strSearch, $matches)) { print_r($matches); } PHP: