简体   繁体   English

如何使用 PHP preg_replace 交换字符串?

[英]How do I swap strings using PHP preg_replace?

I have CSS code and I want to swap left with right and right with left .我有 CSS 代码,我想将left 与 rightright 与 left交换。

Here is example CSS:这是示例 CSS:

.test{text-align:left;margin-left:10px;float:right}
.test_right{text-align:left;border-right:0px;border-left:1px}
.test_left{float:right}

Should be:应该:

.test{text-align:right;margin-right:10px;float:left}
.test_right{text-align:right;border-left:0px;border-right:1px}
.test_left{float:left}

I have the following preg_replace, but it only matches 1 instance in each {} and I need it to match all instances.我有以下 preg_replace,但它只匹配每个 {} 中的 1 个实例,我需要它来匹配所有实例。

$css = preg_replace('/({.*?)left(.*?})/i', '$1right$2', $css);

The other problem with this is that I can't swap left and right because everything would be right after I run the first preg_replace.另一个问题是我不能左右交换因为在我运行第一个 preg_replace 后一切都会正确 How could I solve that issue?我怎么能解决这个问题? Perhaps using preg_replace_callback?也许使用 preg_replace_callback?

I was able to successfully figure it out.我能够成功地弄清楚。

function callback($match)
{
    $matchit = strtr($match[0], array('left' => 'right', 'right' => 'left'));
    return $matchit;
}

$css= preg_replace_callback('/{(.*?)}/i', 'callback', $css);
echo $css;

The preg_replace_callback is returning anything between { and }. preg_replace_callback 返回 { 和 } 之间的任何内容。 The callback function is replacing left and right.回调函数正在替换左右。

I am further refining this function to add some kind of ignore trigger so the PHP will ignore certain classes/IDs.我正在进一步完善此函数以添加某种忽略触发器,以便 PHP 将忽略某些类/ID。 Also, it will need to do some reversing on padding and margin, among other things.此外,它还需要对填充和边距等进行一些反转。 The entire thing will be made into a class for anyone using PHP to convert CSS to RTL easily.整个事情将被制作成一个类,供任何使用 PHP 轻松将 CSS 转换为 RTL 的人使用。

Update:更新:

You can use this preg_replace instead:你可以使用这个 preg_replace 代替:

$css = preg_replace_callback('/{(?!\/\*i\*\/)(.*?)}/i', 'callback', $css);

Then you can put /*i*/ into any line you want it to ignore.然后您可以将 /*i*/ 放入您希望它忽略的任何行中。 For example:例如:

.test{/*i*/margin-left:0px;text-align:right}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM