php preg_match_all和preg_replace。

时间:2013-09-26 07:12:26

标签: php

[caption id="attachment_1342" align="alignleft" width="300" caption="Cheers... "Forward" diversifying innovation to secure first place. "][/caption] A group of 35 students from...

我正在从api读取这些数据。我希望文本以A group of 35 students from...开头。帮我用null替换caption标签。这就是我试过的:

echo "<table>";
echo "<td>".$obj[0]['title']."</td>";
echo "<td>".$obj[0]['content']."</td>";
echo "</table>";
$html = $obj[0]['content'];
preg_match_all('/<caption>(.*?)<\/caption>/s', $html, $matches);
preg_replace('',$matches, $obj[0]['content']);

任何帮助。

4 个答案:

答案 0 :(得分:1)

$pattern = "/\[caption (.*?)\](.*?)\[\/caption\]/i";
$removed = preg_replace($pattern, "", $html);

答案 1 :(得分:1)

 echo preg_replace("#\[caption.*\[/caption\]#u", "", $str);

答案 2 :(得分:0)

在问题中提到的代码段中,正则表达式搜索模式不正确。输入中没有<caption>。它的<caption id...

第二次使用preg_replace在这里没有任何用处。 preg_replace需要三个参数。首先应该是搜索的正则表达式模式。第二个要替换的字符串。第三个是输入字符串。

使用preg_match的代码段将有效。

<?php

//The input string from API
$inputString = '<caption id="attachment_1342" align="alignleft" width="300" caption="Cheers... "Forward" diversifying innovation to secure first place. "></caption> A group of 35 students from';

//Search Regex
$pattern = '/<caption(.*?)<\/caption>(.*?)$/';

//preg_match searches inputString for a match to the regular expression given in pattern
//The matches are placed in the third argument.
preg_match($pattern, $inputString, $matches);

//First match is the whole string. second if the part before caption. third is part after caption.
echo $matches[2];
// var_dump($matches);

?>

如果由于某种原因仍想使用preg_match_all。以下片段是对上述问题的修改 -

<?php

//Sample Object for test
$obj = array(
    array(
        'title' => 'test',
        'content' => '<caption id="attachment_1342" align="alignleft" width="300" caption="Cheers... "Forward" diversifying innovation to secure first place. "></caption> A group of 35 students from'
    )
);

echo "<table border='1'>";
echo "<td>".$obj[0]['title']."</td>";
echo "<td>".$obj[0]['content']."</td>";
echo "</table>";

$html = $obj[0]['content'];

//preg_match_all will put the caption tag in first match
preg_match_all('/<caption(.*?)<\/caption>/s', $html, $matches2);

//var_dump($matches2);

//use replace to remove the chunk from content
$obj[0]['content'] = str_replace($matches2[0], '', $obj[0]['content']);

//var_dump($obj);

?>

答案 3 :(得分:0)

谢谢你们。我使用explode函数来做到这一点。

$html = $obj[0]['content'];
    $code = (explode("[/caption]", $html));
    if($code[1]==''){
    echo $code[1];  
    }   
相关问题