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

标签 php css right-to-left

我有许多为从左到右的网站制作的 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 生成 2 个不同的文件,而不是获取一个文件并生成其镜像,尤其是当您考虑边框等属性而不仅仅是对齐时。

我还没有实际测试过这个,但它应该让你知道如何处理它

<?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 预处理器来为您完成这种繁重的工作,因为这是它们最擅长的。

关于php - 如何将 CSS 文件中的 LTR(从左到右)属性和值转换为 RTL 对应项,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12410792/

相关文章:

internet-explorer-9 - 带边框半径的 IE9 样式

android - RecyclerView 从右到左增长元素

css - SASS从另一个参数获取边框颜色?

PHP 不区分大小写的 explode()

php - 如何使用一种表单中的两个按钮执行不同的 JavaScript 操作?

php - 如何使用PHP中的Predis库检查redis服务器是否正在运行

javascript - 按钮的文本垂直和水平对齐问题

android - 在阿拉伯语的 RTL 中单独获取密码字段错误

ios - 检测 UITextView 文本方向

php - PHP 中 ES6 模板文字的等价物?