你好,
我想从字符串中删除特定字符序列之前和之后的所有内容。
例如:
$string = 'TESTING<html>This is a string</html>ANOTHER TEST!!';
我希望你能够删除
<html>
和 </html>
之前和之后的所有内容,以便在将其写入数据库时,该字符串看起来像这样:<html>This is a string</html>
重要的是,这里的字符串中保留了
<html>
和</html>
。有人有想法吗?可以使用正则表达式来完成:
$str = 'TESTING<html>This is a string</html>ANOTHER TEST!!';
preg_match_all('/(<html>.*<\/html>)/', $str, $matches);
print_r($matches[1][0]);
$str = 'TESTING<html>This is a string</html>ANOTHER TEST!!';
preg_match_all('/(<html>.*<\/html>)/m', $str, $matches);
print_r($matches[1][0]);
试试这样做:
// vars
$string = ' This is text before <html> and this is the text in between </html> And after there is some more text.. ';
$first = '<html>';
$last = '</html>';
// job
$start = stripos($string, $first); // first occurrence position
$length = strripos($string, $last); // last occurrence position
$newString = substr($string, $start, ($length-$start+strlen($last)));
// output
var_dump($string,$start,$length,$newString);
除了已发布的答案,您还可以使用strstr()
函数来获取文本之前和之后的内容,例如:
$newstring = '<html>' . strstr($string, '<html>');
$newstring = strstr($newstring, '</html>', true) . '</html>';
'<html>'
不是一个字符,它是一个字符串。 - BDL