2012-08-28 44 views
0

用下面的字符串:定制SUBSTR PHP

$string='some text <photo id="id#" /> some text'; 

做一个SUBSTR,如果其字符串的结尾是

<photo id="id#" /> 

部分再申请额外的块来完成

"<photo id="id#" />" 

示例:

substr($string,0,15); 

结果是:

some text <phot 

如果这种情况发生,我需要直到结束:

some text <photo id="id#" /> 

他,也找不到这样的方式。顺便说一句,id#是一个随机数值,其长度不会超过3个字符。如果正则表达式有必要提供一个函数。

+1

你有没有考虑一个DOM解析器? – Brad

+0

你需要照顾的标签只是照片或你必须关心不同的标签? – Eineki

+1

请不要使用正则表达式解析HTML,因为它会[驱动你的į̷̷͚̤̤̖̦͍͗̒̈̅̄n̨͖͓̹͍͎͔͈̝͐ͪ͛̄͛ṣ̷̵̞̦ͤ̅̉̋ͪ͑͛ͥ͜a̷̘͖̮͔͎͛̇̏̒͆̆͘n͇͔̤̼͙̩͖̭ͤ͋̉͌͟eͥ͒͆ͧͨ̽͞҉̹͍̳̻͢](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 )。改为使用[HTML解析器](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php)。 –

回答

2

看到这个: -

输出: -

enter image description here

<?php 

$str= 'some text <photo id="#xx"/> some test'; 
$parts = preg_split('~(</?[\w][^>]*>)~', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 
echo '<pre>'; 
print_r($parts); 
echo htmlentities($parts[1]); 


$str_new= 'some text <photo id="#xx"></photo> some test'; 
$parts_new = preg_split('~(</?[\w][^>]*>)~', $str_new, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 
echo '<pre>'; 
print_r($parts_new); 
echo htmlentities($parts_new[1]); 
echo htmlentities($parts_new[2]); 

?> 
0

无需使用正则表达式,只需使用PHP字符串函数:

$string = 'some text <photo id="id#" /> some text'; 
$newString = substr($string, 0, strpos($string, '>') + 1);