我编写这段代码来替换从右到左和从左到右的 css 选择器,但是当我运行它时,不替换任何文本,并返回源代码。
<?php
$headerString = 'Content-type: text/plain; charset="utf-8"';
header($headerString);
$file = 'test.css';
$cssFile = file_get_contents($file);
$pattern1 = '/(\.|\#).*(left|right).*[\n| | |\n\n|\n ]\{/';
preg_match_all($pattern1, $cssFile, $matches);
$matches = $matches[0];
$patternT = array();
$replacementT = array();
foreach ($matches as $key1 => $val1) {
$patternT[$key1] = preg_replace(array(
'/\./',
'/\#/',
'/\:/',
'/\,/',
'/\(/',
'/\)/',
'/\//',
'/\%/',
'/\;/',
'/\{/',
'/\}/',
), array(
'\.',
'\#',
'\:',
'\,',
'\(',
'\)',
'\/',
'\%',
'\;',
'\{',
'\}',
), $val1);
}
foreach ($patternT as $key2 => $val2) {
$patternT[$key2] = '/'.$val2.'/';
}
foreach ($matches as $key3 => $val3) {
$replacementT[$key3] = preg_replace(array(
'/right/',
'/left/',
), array(
'123456789right123456789',
'123456789left123456789',
), $val3);
}
foreach ($replacementT as $key4 => $val4) {
$replacementT[$key4] = preg_replace(array(
'/123456789right123456789/',
'/123456789left123456789/',
), array(
'left',
'right',
), $val4);
}
//Work
echo preg_replace($patternT[1], $replacementT[1], $cssFile);
//Not work
echo preg_replace($patternT, $replacementT, $cssFile);
?>
最佳答案
那么...等等,您只是想将左
和右
相互切换?
最简单的,只需执行 $out = strtr($in,array("left"=>"right","right"=>"left"));
这可能会干扰其他事情 - 例如,如果背景图像中有 leftarrow.png
,它会更改为 rightarrow.png
.. . 也许这是件好事,但如果不是...
$out = preg_replace_callback("/\b(?:right|left)\b/",function($m) {
if( $m[0] == "left") return "right";
return "left";
},$in);
关于php - 我的代码有什么错误? (php),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22248743/