gpt4 book ai didi

php - 使用 preg_replace_callback 对属性进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:08 25 4
gpt4 key购买 nike

所以...所有属性都已完美排序

但是

如何将它们替换(/合并)回原来的 $css 值?

这段代码几乎是不言自明的,但我已经添加了我期望得到的内容以防万一……这里需要进行一些小调整:)

<?php

function mySort($arr) {

$arr = explode( ";" , $arr);
sort($arr);
array_shift($arr);

$returnMe = NULL;

foreach ($arr as $key) {
$returnMe .= $key.';';
}

unset($arr);

return $returnMe."\r\n";

}

$css = <<<EOF

body {
z-index:9;
padding:0;
margin:0;
line-height:10px;
}

p {
z-index: 9;
font-size: 10px;
}

h1,h2,h3,h4,h5,h6 {
z-index: 2;
padding: 0;
margin: 0;
font-size: 100%;
border: 0 none;
}

EOF;


echo '<pre>'.
preg_replace_callback( '~.*?{(.*?)}~s',
function ($match) {
return mySort( $match[1] );
}
,$css )
.'</pre>';

我希望得到:

body {
line-height:10px;
margin:0;
padding:0;
z-index:9;
}

p {
font-size: 10px;
z-index: 9;
}

h1,h2,h3,h4,h5,h6 {
border: 0 none;
font-size: 100%;
margin: 0;
padding: 0;
z-index: 2;
}

最佳答案

您正在匹配 CSS 选择器,但并未将其添加回返回值 - 它只是被回调函数替换

所以您需要做的是也捕获这些部分,并从回调中返回它们,如下所示:

echo '<pre>'.
preg_replace_callback( '~(.*?{)(.*?)(})~s', function ($match) {
return $match[1] . mySort( $match[2] ) . $match[3];
}
,$css )
.'</pre>';

关于php - 使用 preg_replace_callback 对属性进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22571666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com