Mokhtarabadi
Mokhtarabadi

Reputation: 351

What is error in my code? (php)

I write this code to replace right to left and left to right css selectors but when i run this , not replacing any text , and return source code .

<?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);

    ?>

Upvotes: 0

Views: 82

Answers (2)

Firoz
Firoz

Reputation: 486

try using str_replcae function in this case because you know the string. I am not a great fan of JS that is why i am suggesting this:

 str_replace('/\./', '\.', $pattern1);

I hope this helps you. Do the rest by using loop.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

So... wait, you just want to switch left and right with each other?

At its simplest, just do $out = strtr($in,array("left"=>"right","right"=>"left"));

There's a possibility this might interfere with other things - for instance, if you have leftarrow.png in a background image, it would change to rightarrow.png... maybe that's a good thing, but if it's not...

$out = preg_replace_callback("/\b(?:right|left)\b/",function($m) {
    if( $m[0] == "left") return "right";
    return "left";
},$in);

Upvotes: 1

Related Questions