Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 替换下一次出现的标记_Php_Str Replace - Fatal编程技术网

Php 替换下一次出现的标记

Php 替换下一次出现的标记,php,str-replace,Php,Str Replace,我得到了一个带有一些标记的大字符串,我想更改它,以便它与fpdf一起工作 <span style="text-decoration: underline;">some text</span> 一些文本 我需要把这里的标签换成 <i>some text</i> 一些文本 然而,一个简单的str_replace();无法工作,因为存在不应更换的范围标记。我需要制作一些可以找到 然后查找下一个出现的,并仅替换它。我一点儿也不知道怎么做。我已经看过

我得到了一个带有一些标记的大字符串,我想更改它,以便它与fpdf一起工作

<span style="text-decoration: underline;">some text</span>
一些文本
我需要把这里的标签换成

<i>some text</i>
一些文本
然而,一个简单的str_replace();无法工作,因为存在不应更换的范围标记。我需要制作一些可以找到

然后查找下一个出现的
,并仅替换它。我一点儿也不知道怎么做。我已经看过了,但不确定如何实现,以及这是否是解决方案。谁能给我一些指点吗


谢谢

这应该可以做到:

<?php
    $in = '<span>Invalid</span><span style="text-decoration: underline;">some text</span><span>Invalid</span>';
    $out = preg_replace('@<span style=".*">([^<]+)<\/span>@', '<i>\1</i>', $in);
    echo $out;
?>

您还可以限制要在标记中查找的文本,例如,仅限字母数字和空格:

<?php
    $in = '<span>Invalid</span><span style="text-decoration: underline;">some text</span><span>Invalid</span>';
    $out = preg_replace('@<span style=".*">([\w|\s]+)<\/span>@', '<i>\1</i>', $in);
    echo $out;
?>

$dom=新的domDocument;
$dom->loadHTML($html);
$spans=$dom->getElementsByTagName('span');
foreach($span作为$node){
$text=$node->textContent;
$node->removeChild($node->firstChild);
$fragment=$dom->createDocumentFragment();
$fragment->appendXML('.$text'');
$node->appendChild($fragment);
}
$out=preg_replace('/^/','',str_replace(数组('''','',''),数组(''','',''),$dom->saveHTML());
$dom = new domDocument;
$dom->loadHTML($html); 
$spans = $dom->getElementsByTagName('span');
foreach ($spans as $node){
    $text = $node->textContent;
    $node->removeChild($node->firstChild);
    $fragment = $dom->createDocumentFragment();
    $fragment->appendXML('<i>'.$text.'</i>');
    $node->appendChild($fragment);
}
$out = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));