9

这就是我所拥有的

$str = 'Just a <span class="green">little</span> -text åäö width 123#';

这就是我需要的

结果跨度和空格,也可能是换行符。

$result = '<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span>';

你可能想知道我可能需要这个做什么。我想构建一个用块表示字符的东西。看起来有点像 Windows XP 上的碎片整理。

问题

  • 将每个字符替换为<span></span>.
  • 不要触摸字符串中已经存在的 HTML 跨度(可能很难?)。可以有多个 HTML 元素。
  • 不要触摸空格和换行符。
  • 正则表达式应该这样做吗?还是 Xpath?

到目前为止我做了什么?

我找到了关于正则表达式的文章,但没有替换每个字符(摘录空格和换行符)

$result = preg_replace("/???/", "<span></span>", $str);
print_r($result);
4

7 回答 7

2

您可以使用preg_replace_callback()

$str = 'Just a <span class="green">little</span> -text åäö width 123#';

function replacement($matches) {
            if (strlen($matches[0]) == 1) 
            {
                return "<span></span>";
            }
            else 
           {
               return $matches[0];
           }
}

$result = preg_replace_callback("~<span.*?<\s*/\s*span>|\S~", "replacement", $str);
print_r($result);

这只是根据匹配计算替换字符串。如果匹配的长度为 1(已找到非空白字符),则替换为“span”标签,否则已找到 span 标签,重新插入。

于 2013-04-30T11:08:23.493 回答
1

是否要求只使用一个正则表达式?

如果不是 - 你可以用一些唯一字符替换你需要安全的子字符串,用正则表达式执行替换,放置子字符串而不是那个唯一字符。

像这样:

$str2 = str_replace('<span class="green">little</span>', '$', $str);
$str3 = preg_replace("/([^\s\n\$])/", "<span></span>", $str2);
$result = str_replace('$', '<span class="green">little</span>', $str3);

查看现场演示http://codepad.viper-7.com/7wu9fd

升级版:

也许它应该被视为暗示。我的建议是存储需要存储的子字符串,替换您需要的所有内容,将存储的值放回字符串中。

$str = 'Just a <span class="green">little</span> -text åäö width 123#';

preg_match_all('/<[^>]+>/', $str, $matches);
$storage=array();
for($i=0, $n=count($matches[0]); $i<$n; $i++)
{
    $key=str_repeat('$', $i+1);
    $value=$matches[0][$i];
    $storage[$key]=$value;
    $str=str_replace($value, $key, $str);
}
$storage=array_reverse($storage);

$str = preg_replace("/([^\s\n\$])/", "<span></span>", $str);
foreach($storage as $k=>$v)
{
    $str=str_replace($k, $v, $str);
}
echo htmlspecialchars($str);

工作演示在那里http://codepad.viper-7.com/L4YZOz

于 2013-04-30T10:33:35.970 回答
1

不需要 hacky 正则表达式解决方案。带有状态机的简单 for 循环应该就可以了:

define('STATE_READING', 1);
define('STATE_TAG', 2);

$str = 'Just a <span class="green">little</span> -text åäö width 123#';
$result = '';

$state = STATE_READING;
for($i = 0, $len = strlen($str); $i < $len; $i++) {
    $chr = $str[$i];

    if($chr == '<') {
        $state = STATE_TAG;
        $result .= $chr;
    } else if($chr == '>') {
        $state = STATE_READING;
        $result .= $chr;
    } else if($state == STATE_TAG || strlen(trim($chr)) === 0) {
        $result .= $chr;
    } else {
        $result .= '<span></span>';
    }
}

如果我们正在读取标签或单个字符,此循环只是跟踪。如果是标签(或空格),则追加实际字符,否则追加<span></span>

结果是:

<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span>
于 2013-04-30T20:15:29.603 回答
0

虽然这可能通过正则表达式实现,但我会使用循环。下面的示例代码适用于单字节字符集,但可以针对多字节(例如 UTF-16)或可变字节(例如 UTF-8)字符集进行修改。

$input = 'Just a <span class="green">little</span> -text åäö width 123#';
$output = '';
$length = strlen($input);
$i = 0;
$matches = array(); // preg_match variable
// While for finer control
while($i < $length) {
    // Check for start of span tag, check for < character first for speed-up
    if($input[$i] == "<" && preg_match("#<span[^>]*>.*</span>#siU", substr($input, $i), $matches) == 1) {
        // Skip the span tag
        $i = $i + strlen($matches[0]);
        $output .= $matches[0];
    } else {
        $output .= "<span></span>";
        $i++;
    }
}

工作示例

于 2013-04-30T10:38:18.057 回答
0

有点黑客,但试试这个:

$str="Just a <span class=\"green\">little</span> -text åäö\n width 123#";

// get all span tags
if(preg_match_all("/(\<span.*\<\/span\>)/", $str, $matches))
{
    // replace spans with #
    $str=preg_replace_all("/(\<span.*\<\/span\>)/", "#", $str);

    //print_r($matches);
}
// replace all non spaces, CR and #
$str=preg_replace("/[^\s\n#]/", "<span></span>", $str);
// replenish the matched spans
while(list($key,$value)=each($matches[0]))
{
    $str=preg_replace('/#/', $value, $str, 1);
}
于 2013-04-30T10:40:15.850 回答
0

所以这就是我想出的使用preg_replace_callback()

$str = 'Just a <span class="green">little</span>-text åäö width 123#<span>aaa</span> lol';

// This requires PHP 5.3+
$output = preg_replace_callback('#.*?(<span[^>]*>.*?</span>)|.*#is', function($m){
    if(!isset($m[1])){return preg_replace('/\S/', '<span></span>', $m[0]);}
    $array = explode($m[1], $m[0]);
    $array = preg_replace('/\S/', '<span></span>', $array);
    return(implode($m[1], $array));
}, $str);
echo($output);

输出:

<span></span><span></span><span></span><span></span> <span></span> <span class="green">little</span><span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span>aaa</span> <span></span><span></span><span></span>
于 2013-04-30T11:06:38.403 回答
0

这不是一个 hacky 正则表达式方法。这是一个可靠、简洁、单行单函数调用的解决方案,它避免了对字符串中的每个字符重复一系列条件、保留标签并处理多字节字符。

alexn 的解决方案不保持åäö. 他的解决方案将在屏幕上打印 6 个开始和结束跨度标签,而不仅仅是 3 个。这是因为mb_没有使用函数。在这个主题上,请注意此页面上不使用mb_前缀字符串函数的任何方法。

我建议的解决方案将利用该(*SKIP)(*FAIL)技术忽略/取消所有遇到的标签,然后仅匹配字符串中的非空白字符。

代码:(演示

$str = 'Just a <span class="green">little</span> -text åäö width 123#';
var_export(preg_replace('/<[^>]*>(*SKIP)(*FAIL)|\S/','<span></span>',$str));  // no "u" flag means åäö will be span x6
echo "\n";
var_export(preg_replace('/<[^>]*>(*SKIP)(*FAIL)|\S/u','<span></span>',$str)); // "u" flag means åäö will be span x3

输出:(向右滚动查看 unicode 标志对模式的影响)

'<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span>'
// notice the number of replacements for åäö ->-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------111111111111122222222222223333333333333444444444444455555555555556666666666666
'<span></span><span></span><span></span><span></span> <span></span> <span class="green"><span></span><span></span><span></span><span></span><span></span><span></span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span> <span></span><span></span><span></span><span></span><span></span> <span></span><span></span><span></span><span></span>'
// notice the number of replacements for åäö ->-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------111111111111122222222222223333333333333
于 2017-11-15T02:50:48.613 回答