2013-09-26 71 views
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...php preg_match_all和preg_replace。

我正在从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']); 

任何帮助。

回答

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

谢谢。我使用爆炸功能来做到这一点。 $ html = $ obj [0] ['content']; \t $ code =(explode(“[/ caption]”,$ html)); \t if($ code [1] ==''){ \t echo $ code [1]; \t \t} – Parthi

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

谢谢。我使用爆炸功能来做到这一点。 $ html = $ obj [0] ['content']; \t $ code =(explode(“[/ caption]”,$ html)); \t if($ code [1] ==''){ \t echo $ code [1]; \t \t} – Parthi

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

?> 
+0

谢谢。我使用爆炸功能来做到这一点。 $ html = $ obj [0] ['content']; \t $ code =(explode(“[/ caption]”,$ html)); \t if($ code [1] ==''){ \t echo $ code [1]; \t \t} – Parthi

0

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

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