PHP Regex to match words with dash right infront and save to array? -
i'm wondering kind of regex use extract words have dash infront of them in given string. i'm going using allow users omit words search results of website.
for example, have
$str = "this search -test1 -test2";
i'm trying have save "test1"
, "test2"
array because have dash right infront.
could me out
use following pattern /\-(\w+)/
. example:
$string = 'this search -test1 -test2'; $pattern = '/\-(\w+)/'; if(preg_match_all($pattern, $string, $matches)) { $result = $matches[1]; } var_dump($result);
output:
array(2) { [0] => string(5) "test1" [1] => string(5) "test2" }
explanation:
/.../ delimiter chars \- dash (must escaped has special meaning in regex language (...) special capture group. stores content between them in $matches[1] \w+ @ least 1 ore more word characters
Comments
Post a Comment