doumen9709 2017-11-08 09: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 09: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 . 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?