doumen9709 2017-11-08 01:24
浏览 42
已采纳

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

So I have this string that looks like this:

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

and I want to output it like this:

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

Im done with the /O thing i did it with just preg_replace what my problem is the Microsoft/ORGANIZATION i need the REGEX for this. I tried finding the word first using this:

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

1条回答 默认 最新

  • dongyan3562 2017-11-08 01:39
    关注

    preg_replace solution:

    $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);
    

    The output:

    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 . 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部