Page 1 of 1

Preg_split help needed..

Posted: Mon Nov 24, 2008 3:45 pm
by kaisellgren
Hi,

Code: Select all

$data = "this is a test string. This is another test. And another. But \. this hope fully does not get split up. While \\. this should be ;)";
$split = preg_split("#\\.#",$data);
I want to split the text into parts using the dot. I don't need the dot to be a part in the splitted content. Actually I want the dot be gone. This is all easy, but when it comes to taken those backslashes into consideration, it's harder...

The "\." should not be counted to be splitten... Doing something like

Code: Select all

$split = preg_split("#[^\\]\\.#",$data);
Will work OK, but the problem here is that the preg_split will take the character near the dot away and it does not exist in the splitted strings...

Also "text. \\. test" should be 2 parts... so I need a completely working splitting. The escaping can be anything, it might be "\\\\\\\\\\." and it must be handled correctly, MUST be...

Any help?

Re: Preg_split help needed..

Posted: Mon Nov 24, 2008 4:13 pm
by John Cartwright

Code: Select all

$result = preg_split('#\.(?=\\)#', $subject, 2);
It's been quite some time since I've used regex, but what you are looking for is called a negative lookahead. Assuming that example doesn't work (untested), that page should sort you out.

Good luck.

Re: Preg_split help needed..

Posted: Mon Nov 24, 2008 5:05 pm
by kaisellgren
Jcart wrote:

Code: Select all

$result = preg_split('#\.(?=\\)#', $subject, 2);
It's been quite some time since I've used regex, but what you are looking for is called a negative lookahead. Assuming that example doesn't work (untested), that page should sort you out.

Good luck.
Yeah that works pretty well, but there are situations where it does not work. Like "this should not be splitted \\\. in half" while "this should be splitted \\. in half".

Re: Preg_split help needed..

Posted: Tue Nov 25, 2008 12:54 am
by John Cartwright
If I'm not mistaken, it should not match any period that is preceeded by a backslash. Sorry I'm rusty.

Re: Preg_split help needed..

Posted: Tue Nov 25, 2008 12:46 pm
by kaisellgren
Jcart wrote:If I'm not mistaken, it should not match any period that is preceeded by a backslash. Sorry I'm rusty.
Yes. I actually solved this, it's rather Hacky method.. I'm looping with For and changing $esc = true/false etc... but it's fine for me use ...

Re: Preg_split help needed..

Posted: Thu Nov 27, 2008 1:52 pm
by John Cartwright
Did you try my method? It should do exactly what I just said..