使用preg_replace在php中的两个字符串之间用单引号替换引号

问题描述 投票:0回答:1

我正在寻找一个 preg_replace ,可以在 font-family: 和 ; 之间用 ' 替换 "

我正在使用的一些动态 html 遇到问题,这需要我将样式属性中的引号替换为单引号。当字体和字体系列属性的名称中包含空格时,有时可能会包含引号,但这会导致渲染 html 时出现问题。我还没有完全掌握如何使用 preg_replace 所以我希望有人能帮我一把。

这是字符串的示例:

<span style="font-weight:bold;font-family:"franklin gothic medium",arial,helvetica,sans-serif;font-size:29px"="">Made in the USA!</span>

从我认为 preg_replace 的工作方式来看,我尝试了以下方法,但它不起作用:

preg_replace("/font\-family\:[\"]+?\;/", "'", $string);

php regex preg-replace
1个回答
0
投票

回答

<?php
$pattern = '/font-family:\s*"([^"]*)"/';
$result = preg_replace_callback($pattern, function($matches) {
    return 'font-family: \'' . $matches[1] . '\'';
}, $string);

测试

<?php

$string = 'font-family: "font"; content: "A";';

$pattern = '/font-family:\s*"([^"]*)"/';
$result = preg_replace_callback($pattern, function($matches) {
    return 'font-family: \'' . $matches[1] . '\'';
}, $string);

echo $result; // font-family: 'font'; content: "A";
© www.soinside.com 2019 - 2024. All rights reserved.