如何删除字符串

时间:2015-11-30 08:19:08

标签: php regex

我有一个这样的字符串:

$str = '<div class="content"><br /> 
<strong>0730</strong> – Check in direct to Compass at Marlin Wharf Berth 18</p> <p><strong>0800 </strong> – Depart Marlin Marina Cairns to the Great Barrier Reef</p> 
<p><strong>1015</strong> – Arrive at your first Great Barrier Reef Location</p> <p><strong>1230</strong> – BBQ Lunch with fresh salads</p> 
<p><strong>1300</strong> Cruise to 2nd Reef Location 1530 – Depart the Great Barrier Reef</p> 
<p><strong>1730</strong> – Approximately Arrival time at Cairns Marina<br /> </div>';

我想使用preg_replace函数删除第一个</p>和最后<p>代码,因为它们是多余的,我使用了这种模式,但它没有用。

$patterns = array(
            '#^\s*</p>#',
            '#<p>\s*$#',
);

$str = preg_replace( $patterns, '', $str );

3 个答案:

答案 0 :(得分:2)

您可以使用一个表达式执行此操作:

$str = preg_replace("#(.*?)</p>(.*)<p>(.*)#s", "$1$2$3", $str, 1 );

这将在第一个</p>之前进行非贪婪的文本捕获,然后贪婪地捕获文本直到<p>(由于贪婪,这将是最后一个)。最后,还会捕获剩余的文本。保留了三个捕获的组,2个标记不是。

需要s修饰符以允许点也匹配换行符。

请注意,这不会检查是否确实需要删除。它只是这样做,所以如果HTML已经没问题,你将得到一个不理想的结果。

答案 1 :(得分:2)

这应该做你需要的事情

$str = '<div class="content"><br />
<strong>0730</strong> – Check in direct to Compass at Marlin Wharf Berth 18</p> <p><strong>0800 </strong> – Depart Marlin Marina Cairns to the Great Barrier Reef</p>
<p><strong>1015</strong> – Arrive at your first Great Barrier Reef Location</p> <p><strong>1230</strong> – BBQ Lunch with fresh salads</p>
<p><strong>1300</strong> Cruise to 2nd Reef Location 1530 – Depart the Great Barrier Reef</p>
<p><strong>1730</strong> – Approximately Arrival time at Cairns Marina<br /> </div>';

//Replace the first one, easy enough
$str = preg_replace('/<\/p>/', "", $str, 1);

$stringReplace = "<p>";
$stringLen = strlen($stringReplace);

//Get the position of the last one, with strrpos (reverse check)
$pos = strrpos($str, $stringReplace);

//Make sure there is one
if($pos !== false){
    //If so, replace it with nothing
    $str = substr_replace($str, "", $pos, $stringLen);
}

答案 2 :(得分:-4)

你可以使用这样的东西。但我自己不检查。所以,让我和其他人知道它是否有效。

$text = "Quick \"brown fox jumps \"over\" the lazy\" dog";
$resault = Regex.Replace(text, "(?<=^[^\"]*)\"|\"(?=[^\"]*$)", "\"\"\"");