0

I'm looking for a regular expression pattern that can match adjacent characters in a string in php.

For example if I have the string "1234" I would like it to match and return

1
12
123
1234

Is this possible with regular expressions in php?

I've tried

$testString = '1234';
preg_match_all('/.+/', $testString, $matches);

But that just returns the entire string.

DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70

3 Answers3

1

Using strrev trick it is possible >>

Code:

$s = '1234';
preg_match_all('/(?=(.+$)).?/', strrev($s), $m);
foreach(range(sizeof($m[1]), 0) as $i) print strrev($m[1][$i]) . "\n"; 

Output:

1
12
123
1234

See this demo.


However you should also go with simple solution without regex >>

Code:

$s = '1234';
foreach(range(1, strlen($s)) as $i) print substr($s, 0, $i) . "\n";

Output:

1
12
123
1234

Check this code here.

Ωmega
  • 42,614
  • 34
  • 134
  • 203
0

Is it possible? Yes. Is it reasonable? Probably not.

Here is a demo in Perl, just to show it can be done with your particular example:

#!/usr/bin/perl -l

my $string = "abcd";

my $pattern = qr{
    ^
    (?=  ( .{1} )  )
    (?=  ( .{2} )  )
    (?=  ( .{3} )  )
    (?=  ( .{4} )  )
}x;

my @captures = ($string =~ $pattern);

print for @captures;

Which when run produces this output:

a
ab
abc
abcd

The PCRE library that PHP uses is perfectly capable of doing that. But not even I would do it that way.

And as for arbitrary groupings, that becomes even trickier still, requiring a recursive pattern and even more serious magic. I wouldn’t do that for anything but some sort of extenence-proof sort of programming contest, not for real code that you would hope to maintain, and not get shot for.

tchrist
  • 78,834
  • 30
  • 123
  • 180
-1

No, this can't be (reasonably) done with regular expressions.

That's why loops were invented though. I'm sure it's quite easy to cook something up with a simple for loop.

Example:

$str = "1234";
for ($i = 0; $i < strlen($str); $i++) {
    echo substr($str, 0, $i+1) . "\n";
}
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • 1
    Every man’s level of reasonableness is his own, but I agree that it doesn’t feel natural to use pattern matching for this. – tchrist Sep 28 '12 at 23:17
  • @tchrist: Some things are globally agreed upon not being reasonable. HTML **can** be parsed with regex as well. Doesn't mean it's a good idea. – Madara's Ghost Sep 28 '12 at 23:24
  • 1
    Pretty sure that I’m going on the last person on Earth you need to talk to about [regex-based approaches to parsing HTML](http://stackoverflow.com/questions/4231382/regular-expression-pattern-not-matching-anywhere-in-string/4234491#4234491). – tchrist Sep 28 '12 at 23:30
  • @Ωmega: Please don't edit my code if it doesn't contain syntax errors. Also, don't change the meaning of my answer. – Madara's Ghost Sep 29 '12 at 19:23