doufu9145 2016-05-26 04:55 采纳率: 0%
浏览 61
已采纳

如何获取字符串和替换之间的所有子字符串

I have the following string in php

<?php 

$data = 'The good <b>PEOPLE LIVES LONG</b>. The bad <b>PEOPLE DIES FAST</b>';
   ?>

I want to extract the part between tag and replace it with my own text. here is the function I used to just get the text between the tag.

function GetStringBetween ($string, $start, $finish) {
$string = " ".$string;
$position = strpos($string, $start);
if ($position == 0) return "";
$position += strlen($start);
$length = strpos($string, $finish, $position) - $position;
return substr($string, $position, $length);
}

If I called the function with

    GetStringBetween ($data, '<b>', '</b>')

It works when i.e the data is

    $data = 'The good <b>PEOPLE LIVES LONG</b>.';

But it doesn't work here when the data contains more multiple pairs of i.e when

     $data = 'The good <b>PEOPLE LIVES LONG</b>. The bad <b>PEOPLE DIES FAST</b>';

I need help with function to always replace string between the and with my own text no matter how many times it appears.

  • 写回答

1条回答 默认 最新

  • doson1998 2016-05-26 04:58
    关注

    Did you try preg_match :

    preg_match('/<b>(.*?)<\/b>/i', $string, $matches);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部