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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.