Jump to content

Simple Preg_Match Function


dyluck

Recommended Posts

Hello

 

Trying to figure this out, the function below works fine if the code doens't have to escape anything. 

 

Hopefully someone can help :)

 


function getTextBetweenStrings($string,$front,$back)
{

 $replacefrom = array("/",'^','$','.','[',']','|','(',')','?','*','+','{','}','\\','-');
 $replaceto = array("\/",'\^','\$','\.','\[','\]','\|','\(','\)','\?','\*','\+','\{','\}','\\\\','\-');

 $front = str_replace($replacefrom, $replaceto, $front);
 $back = str_replace($replacefrom, $replaceto, $back);

    $pattern = "/$front(.*?)$back/";
    preg_match($pattern, $string, $matches);
    return $matches;

}


$value = '<h2>GE Profile Black 36 in. Electric Cooktop with Induction Elements</h2>';

echo implode("<br>",getTextBetweenStrings($value, '<h2>', '</h2>'));

 

If you change the  </h2> part to <Bh2> on both the $value and the function variable, it works fine.

 

Thanks :)

Link to comment
https://forums.phpfreaks.com/topic/202682-simple-preg_match-function/
Share on other sites

Hello

 

Trying to figure this out, the function below works fine if the code doens't have to escape anything. 

 

Hopefully someone can help :)

 


function getTextBetweenStrings($string,$front,$back)
{

 $replacefrom = array("/",'^','$','.','[',']','|','(',')','?','*','+','{','}','\\','-');
 $replaceto = array("\/",'\^','\$','\.','\[','\]','\|','\(','\)','\?','\*','\+','\{','\}','\\\\','\-');

 $front = str_replace($replacefrom, $replaceto, $front);
 $back = str_replace($replacefrom, $replaceto, $back);

    $pattern = "/$front(.*?)$back/";
    preg_match($pattern, $string, $matches);
    return $matches;

}


$value = '<h2>GE Profile Black 36 in. Electric Cooktop with Induction Elements</h2>';

echo implode("<br>",getTextBetweenStrings($value, '<h2>', '</h2>'));

 

If you change the  </h2> part to <Bh2> on both the $value and the function variable, it works fine.

 

Thanks :)

 

Just had to remove the following and it worked:  '\\',  '\\\\',

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.