0

[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 替换标题标签。这是我尝试过的:

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

4 回答 4

1
 echo preg_replace("#\[caption.*\[/caption\]#u", "", $str);
于 2013-09-26T07:22:34.397 回答
1
$pattern = "/\[caption (.*?)\](.*?)\[\/caption\]/i";
$removed = preg_replace($pattern, "", $html);
于 2013-09-26T07:18:00.313 回答
0

感谢你们。我使用爆炸功能来做到这一点。

$html = $obj[0]['content'];
    $code = (explode("[/caption]", $html));
    if($code[1]==''){
    echo $code[1];  
    }   
于 2013-09-27T00:41:12.453 回答
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);

?>
于 2013-09-26T07:50:52.050 回答