Jump to content

Matching specific amounts of space and tab characters


Prismatic

Recommended Posts

What I'm working on is complicated but my problem isn't.

 

I'm trying to convert sets of tabs and spaces into other characters.

 

For example, say I have the following.

One tab
	Two tabs
		Three tabs

 

What I'm trying to do is end up with the following

[hl=/t][/hl]One tab
[hl=/t/t][/hl]Two tabs
[hl=/t/t/t][/hl]Three tabs

 

Note the three /t's for the three tabs. My issue is when the script generates the regex to do the first line there, which has one tab, the regex is

/[\t]{1}/

 

But that converts all the tabs. It's hard to explain ugh.

 

All I can manage is

[hl=/t][/hl]One tab
[hl=/t/[/hl][hl=/t][/hl]Two tabs
[hl=/t/][/hl][hl=/t][/hl][hl=/t][/hl]Three tabs

 

 

help?

<?php

function tab_replace($args) {
    $tmp = '[h1='.str_replace("\t",'/t', $args[0]).'][/h1]';
    return $tmp;
}

$text = '
One tab
	Two tabs
		Three tabs
';

$output = preg_replace_callback('/\t+/', 'tab_replace', $text);
echo $output;

<?php

function tab_replace($args) {
    $tmp = '[h1='.str_replace("\t",'/t', $args[0]).'][/h1]';
    return $tmp;
}

$text = '
One tab
	Two tabs
		Three tabs
';

$output = preg_replace_callback('/\t+/', 'tab_replace', $text);
echo $output;

 

That works great thank you :)

 

[h1=/t][/h1]This text is inside the pre element, it will be parsed.
[h1=/t][/h1]Tabbed text
[h1=/s/s][/h1]Two spaces
[h1=/s/s/s][/h1]Three spaces
[h1=/s/s/s/s][/h1]four spaces[h1=/t][/h1]and a tab
[h1=/t/t][/h1]Two tabs

 

Adapted it for spaces 2+

 

$output = preg_replace_callback("/[ ]{2,}/", "space_replace" , $output);

...

function space_replace($args)
{
	$tmp = '[h1='.str_replace(" ",'/s', $args[0]).'][/h1]';
    return $tmp;
}

 

 

Cheers!

 

 

Edit - where's the solved button at?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.