You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP正则替换<loc>标签内内容并限制长度问题求助

解决XML中标签内容长度限制问题

你的代码无法正常运行的核心问题是:直接在替换字符串中调用mb_strimwidth('$2', 0, 15)时,'$2'只是普通字符串,不是正则捕获到的实际URL内容,导致替换结果错误。

正确的做法是使用preg_replace_callback,通过回调函数处理每个匹配到的内容,具体修正代码如下:

<?php
$string = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    <url>
    <loc>https://subdomain.example.com</loc>
    <priority>1.0</priority>
    <changefreq>always</changefreq>
    </url>
    <url>
    <loc>https://subdomain.example.com/s/queen-katwe-2016-720p-hd-480p-hd/</loc>
    <priority>1.0</priority>
    <changefreq>always</changefreq>
    </url><url>
    <loc>https://subdomain.example.com/s/justice-league-dark-2017-720p-hd-480p-hd/</loc>
    <priority>1.0</priority>
    <changefreq>always</changefreq>
    </url><url>
    <loc>https://subdomain.example.com/s/edge-seventeen-2016-720p-hd-480p-hd/</loc>
    <priority>1.0</priority>
    <changefreq>always</changefreq>
    </url></urlset>';

// 正则匹配<loc>标签及其内容,通过回调处理每个匹配项
$total = preg_replace_callback(
    '/(<loc>)(.*?)(<\/loc>)/',
    function($matches) {
        // $matches[2] 是<loc>标签内的原始URL
        $trimmedUrl = mb_strimwidth($matches[2], 0, 15);
        // 拼接回完整的<loc>标签结构
        return $matches[1] . $trimmedUrl . $matches[3];
    },
    $string
);

echo $total;
?>

关键说明:

  • preg_replace_callback会遍历所有匹配的标签,回调函数中的$matches数组存储了正则捕获的内容:$matches[1]是<loc>,$matches[2]是标签内的URL,$matches[3]是</loc>。
  • 如果需要在截取后添加省略号,可修改mb_strimwidth的第四个参数,例如:mb_strimwidth($matches[2], 0, 15, '...')。
  • 该方法能保证XML结构不被破坏,仅修改标签内的内容长度。

内容的提问来源于stack exchange,提问作者Godwin Alex Ogbonda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:30:52