【问题标题】:PHP Parse html start and end bracketPHP Parse html 开始和结束括号
【发布时间】:2015-08-14 08:03:51
【问题描述】:

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

这就是我想要做的。我有一个文本区域,我输入了这些信息。

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.
?>

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

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

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

我的城市 y 的具体协议文本

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

我的城市 y 的具体协议文本 2

【问题讨论】:

  • 对不起,你想在这里做什么?匹配偶数行中][ 之间的所有文本?或者实际上评估那些行上初始[…]` 中的表达式?
  • 你试过了吗?请提供一些代码
  • 你想在这里实现什么?不清楚……能详细点吗?
  • 这个正则表达式可能对你有用 \[.*city="y"\](.*)\[\/if\], regex
  • 好吧,详细说明。我要输入的文本是购买在线课程的标准协议的文本。但是该协议是有条件的,具体取决于协议的某些部分您来自哪个城市。因此,如果您来自纽约,那么如果您在伦敦学习课程,那么文本的某些部分会有所不同。

标签: php regex parsing


【解决方案1】:

因此,感谢“匿名”的正则表达式,我可以找到适合我的解决方案。不要认为它是最漂亮的,但它确实有效。

$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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2011-07-10
    • 2011-05-29
    • 2021-04-14
    • 2019-11-05
    相关资源
    最近更新 更多