PHP Parse html开始和结束括号

时间:2015-08-14 08:03:51

标签: php regex parsing

我在使用PHP解析括号中的文本时遇到问题

这是我想要做的。我有一个textarea,我输入这些信息。

Lorem Ipsum is simply dummy text of the printing and typesetting industry

[if city="x"]My specific agreement text for the city x[/if]

Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum is simply dummy text of the printing and typesetting industry

[if city="y"]My specific agreement text for the city y[/if]

Lorem Ipsum is simply dummy text of the printing and typesetting industry

[if city="y"]My specific agreement text 2 for the city y[/if]

然后我想像这样呈现文本。

<?php
$textarea = $_POST['textarea'];
$city = "y";

// DO SOME MAGIC I DON'T KNOW... To remove the text between the [if city="x"]Text[/if] and keep the textsnippets between [if city="y"]Text[/if]

// END OF MAGIC.

echo $textarea // Now the text that are in brackets of city = y only shows.
?>

最终结果应该是这样的(当回声时)

  

Lorem Ipsum只是打印和排版的虚拟文本   业

     

Lorem Ipsum只是打印和排版的虚拟文本   行业。 Lorem Ipsum只是简单的印刷文本和   排版行业

     

我的城市特定协议文本

     

Lorem Ipsum只是打印和排版的虚拟文本   业

     

我针对城市的具体协议文本2

1 个答案:

答案 0 :(得分:0)

感谢#匿名&#34;的正则表达式我可以找到适合我的解决方案。不要认为它是最好的,但它确实有效。

$city = 'x';
$string = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry
<br><br>
[if city="x"]My specific agreement text for the city x[/if]
<br><br>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum is simply dummy text of the printing and typesetting industry
<br><br>
[if city="y"]My specific agreement text for the city y[/if]
<br><br>
Lorem Ipsum is simply dummy text of the printing and typesetting industry
<br><br>
[if city="y"]My specific agreement text 2 for the city y[/if]';


$reg = preg_match_all('(\[if.*](.*)\[\/if\])', $string, $matches);


foreach( $matches[0] as $key => $value ) {
    if( strpos($value,'city="'. $city .'"') !== false ) {

    } else {
        $string = str_replace($value, '', $string);
    }
}

$string = str_replace('[if city="'. $city .'"]', '', $string);
$string = str_replace('[/if]', '', $string);


echo $string;