如何获得与我的REGEX匹配的特定字符串?

时间:2017-11-08 09:24:53

标签: php regex

所以我有这个字符串,如下所示:

  

I / O抱怨/ O / O / Microsoft / ORGANIZATION关于/ O Bill / PERSON   盖茨/ PERSON ./O他们/ O告诉/ O me / O到/ O看/ O / O市长/ O / O   新/ LOCATION约克/位置./O

我希望像这样输出:

I complained to <span class="ORAGANIZATION"> Microsoft</span> about <span class="PERSON">Bill</span>

我完成了/ O的事情我用preg_replace做了我的问题是我的问题是Microsoft / ORGANIZATION我需要这个REGEX。我试着先用这个词找到这个词:

$text_vars = preg_match("/PERSON|ORGANIZATION/", $string, $matches);
$temp = array_shift( $matches );

1 个答案:

答案 0 :(得分:1)

preg_replace 解决方案:

$s = 'I/O complained/O to/O Microsoft/ORGANIZATION about/O Bill/PERSON Gates/PERSON ./O They/O told/O me/O to/O see/O the/O mayor/O of/O New/LOCATION York/LOCATION ./O';
$result = preg_replace('~(\S+)/(ORGANIZATION|PERSON)~', '<span class="$2">$1</span>', 
                       preg_replace('~/O(\s+|$)~', ' ', $s));

print_r($result);

输出:

I complained to <span class="ORGANIZATION">Microsoft</span> about <span class="PERSON">Bill</span> <span class="PERSON">Gates</span> . They told me to see the mayor of New/LOCATION York/LOCATION .