John Mfon
John Mfon

Reputation: 37

How to get all substring between a string and replace

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.

Upvotes: 0

Views: 38

Answers (1)

chandresh_cool
chandresh_cool

Reputation: 11830

Did you try preg_match :

preg_match('/<b>(.*?)<\/b>/i', $string, $matches);

Upvotes: 1

Related Questions