A
A
Akmal Kadirov2015-01-14 21:50:47
PHP
Akmal Kadirov, 2015-01-14 21:50:47

Can you help with one regular expression?

You need to find 2 spaces in a row and replace them with \t
But, you need to replace only those spaces that go before the beginning of any other characters.
For example, the string:
(4-spaces here)Text(4-spaces here too)
Should be replaced with this:
\t\tText(4-spaces here)
If you use
$str = preg_replace('/^ {2}/m', "\t", $str);
That, you get "\t(4-spaces here)Text(4-spaces here) -space)"
Any ideas?
-----------
UPD:
I don't think it's really possible to implement this just using RT.
So the question is removed. Thanks to all!

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Deodatuss, 2015-01-14
@Deodatuss

So? jsfiddle.net/djkyt0c6/1

T
Tyranron, 2015-01-15
@Tyranron

You can add your own logic to the regular expression in PHP.

function replaceSpacesWithTabs($line, $perTab = 2)
{
    return preg_replace_callback('/^[ ]+/', 
        function ($matches) use ($perTab) {
            $len = strlen($matches[0]);
            $out = str_repeat("\t", floor($len / $perTab));
            if (($rem = $len % $perTab) > 0) {
                $out .= str_repeat(' ', $rem);
            }        
            return $out;
        },
        $line
    ); 
}

You can poke here .
On the solution of a purely regular, in my opinion, does not pull. But you can apply it for yourself.

E
Eugene, 2015-01-14
@Nc_Soft

$str = preg_replace('/\A[ ]{2}/m', "\t", $str);

S
Sergey Shchuchkin, 2015-01-14
@shuchkin

was too lazy, left it like that

$str = preg_replace('/\n {4}/',"\n\t", $str);
$str = preg_replace('/\n {4}/',"\n\t", $str);
$str = preg_replace('/\n {4}/',"\n\t", $str);
$str = preg_replace('/\n {4}/',"\n\t", $str);

Z
zed, 2015-01-14
@zedxxx

Is it important for you to do this on a regular basis? The task is elementarily solved by character-by-character scanning of the string with replacement by condition.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question