替换含多余空格的损坏字母数字ID子串技术求助
问题需求
- 动态生成的内容中,订单ID被空格拆分导致损坏,需用持有的完整
orderId替换内容中损坏的订单ID - 已拥有正确的完整
orderId
示例损坏内容
$content = "Order is purchased on 23-05-2023.Order is in progress and you can see order status on website by enter id JKSZ089P6X07 012"; $content = "Order Model is Ford and year model 2017.Order id is 6FTYF75C7HD 715 and Vehicle type is commercial."; $content = "Order Model is Mahindra and year model 2015.Order id is 9PKKJ7FS3CD 890 and Vehicle type is personal.";
现有代码(存在问题)
$orderId = "JKSZ089P6X07A07012"; $getChar = substr(orderId ,0,12); // 语法错误:变量名缺少$符号 if(strpos( $content, $getChar ) !== false ) { echo "found"; $content = str_replace($getChar," ",$content); // 仅替换前缀,未处理损坏ID的剩余部分 } echo $content;
期望输出
$content = "Order is purchased on 23-05-2023.Order is in progress and you can see order status on website by enter id JKSZ089P6X07A07012"; $content = "Order Model is Ford and year model 2017.Order id is 6FTYF75C7HD680715 and Vehicle type is commercial."; $content = "Order Model is Mahindra and year model 2015.Order id is 9PKKJ7FS3CD347890 and Vehicle type is personal.";
解决方案代码
// 替换为实际的完整orderId $orderId = "JKSZ089P6X07A07012"; // 提取完整ID的前12位作为匹配标识 $prefix = substr($orderId, 0, 12); // 正则匹配被空格拆分的损坏ID:前缀+任意空格+数字,替换为完整orderId $content = preg_replace("/{$prefix}\s+\d+/", $orderId, $content); // 将 转换为普通空格,匹配期望输出格式 $content = str_replace(' ', ' ', $content); echo $content;
代码说明
- 提取完整
orderId的前12位,作为定位损坏ID的核心标识 - 用正则表达式精准匹配「前缀+任意数量空格+数字」的损坏ID格式,直接替换为完整
orderId - 额外处理
转普通空格,让输出格式与期望完全一致
内容的提问来源于stack exchange,提问作者parv
相关产品推荐
相关产品推荐

