如何将CSS文件中的LTR(从左到右)属性和值转换为RTL对应项,反之亦然


How to convert LTR(left to right) properties and values in a CSS file to RTL counterparts and vice-versa

我有很多CSS文件是为从左到右的网站制作的

我想创建一个php函数,它可以将LTR属性和值转换为RTL对应的

我之所以想这样做,是因为网站一直在开发中,它有几十个页面和css文件,很难跟踪所有这些

该功能的目的是自动转换CSS文件,因此更容易制作RTL版本的网站

例如:

// This is the content of the css file:
$content = '
html, body {
  direction: ltr;
}
#element1 {
  padding:   1px 2px  3px 4px;
  margin-right: 3em;
  background-position: 5%   80%;
  background-image: url(image.png);
  cursor: ne-resize;
  text-align: left; /* 1 */
}
#element2 {
  background: url(image.gif) 5% 80%;
  text-align: right; /* 2 */
  border-left: 1px solid #000;
}
';
$content = convertCSStoRTL($content);
// The output - This is what i want it to become after the function is applied to the content of the css file:
$content = '
html, body {
  direction: rtl;
}
#element1 {
  padding: 1px 4px 3px 2px;
  margin-left: 3em;
  background-position: 95% 80%;
  background-image: url(image.png);
  cursor: nw-resize;
  text-align: right; /* 1 */
}
#element2 {
  background: url(image.gif) 95% 80%;
  text-align: left; /* 2 */
  border-right:  1px solid #000;
}
';

如何在PHP中(以最简单的方式)做到这一点?

如果你试图依靠正则表达式/str_replace来修改你的CSS,我认为你会受到很大的伤害。我的建议是让PHP生成两个不同的文件,而不是获取一个并生成其镜像,尤其是当您考虑边界等属性而不仅仅是对齐时。

我还没有真正测试过这个,但它应该让你知道如何使用

<?php
$ltr = true;
function doLTR($left, $right, $property = FALSE) {
    @global $ltr;
    $direction = $ltr ? $left : $right;
    if (!$property) {
        print $direction;
    } else {
        print $direction . ': ' . $property;
    }
}
?>
.test {
    border: 1px solid;
    <?php doLTR('margin-left', 'margin-right', '10px'); ?>
    <?php doLTR('text-align: left', 'text-align: right'); ?>
}

如果是$ltr = true,理论上应该得到以下输出:

.test {
    border: 1px solid;
    margin-left: 10px;
    text-align: left;
}

如果它是假的(rtl),你会得到这个:

.test {
    border: 1px solid;
    margin-right: 10px;
    text-align: right;
}

可能值得考虑使用像Sass或LESS这样的CSS预处理器来为您做这种繁重的工作,因为这是他们做得最好的。

下面的SCSS导入添加了一些有用的变量、函数和mixin。

在GitHub 上查看

阅读更多

// Override default value for $dir in directional.scss
$dir: rtl;
// Import helpers from directional.scss
@import "directional";
// Use the helpers to make CSS for LTR or RTL
body {
    text-align: $left;
    padding-#{$right}: 1em;
    margin: dir-values(0 2em 0 1em) if-ltr(!important);
}