duai0935 2017-04-13 11:19
浏览 20
已采纳

在字符串中查找开始和结束引号

I have a string of text as follows:

The nice man said "How's things today" and I replied "All is good thanks".

I would like to replace the double quotes for fontawesome icons. If I do a string replace on double qoutes it works fine. But as expected this just gives me a generic lefthand quote mark for every double quote within the string.

My current code:

$str = The nice man said "How's things today" and I replied "All is good thanks".

$str = str_replace('"', '<i class="fa fa-quote-left" aria-hidden="true"></i>');

Outputs:

The nice man said <i class="fa fa-quote-left" aria-hidden="true"></i>How's things today<i class="fa fa-quote-left" aria-hidden="true"></i> and I replied <i class="fa fa-quote-left" aria-hidden="true"></i>All is good thanks<i class="fa fa-quote-left" aria-hidden="true"></i>.

Desired Output:

The nice man said <i class="fa fa-quote-left" aria-hidden="true"></i>How's things today<i class="fa fa-quote-right" aria-hidden="true"></i> and I replied <i class="fa fa-quote-left" aria-hidden="true"></i>All is good thanks<i class="fa fa-quote-right" aria-hidden="true"></i>.


Example Output: http://jsfiddle.net/JfGVE/1975/
  • 写回答

1条回答 默认 最新

  • doude2635 2017-04-13 11:26
    关注

    If you are sure double quotes are there as the same as what we are seeing in the subject string (balanced, no escaped double quote inside) then a regex will do the job:

    echo preg_replace('~(")([^"]+)(")~', '<i class="fa fa-quote-left" aria-hidden="true"></i>\\2<i class="fa fa-quote-right" aria-hidden="true"></i>', $str);
    

    Live demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图