0

I'm having trouble with this, I did find a couple of reg ex examples but I can't seem to get them to work for me.

$string = '1. A post-hardcore band from Brazil 2. A rock band from Sweden';

I need to retrieve everything inbetween the "1." and "2."

Is there some kind of simple splitting function in PHP that I could use like so?

$result = string_between_chars($string, "1. ", "2 ."); 

Or, if I'm matching for numbers

preg_match('~(1.|2.|3.|4.)~', ($string), $matches

Is there anyway I could modify this to be left with the result of

[0] => 1. A post-hardcore band from Brazil
[1] => 2. A rock band from Sweden
Nick Shears
  • 1,103
  • 1
  • 13
  • 30

3 Answers3

0

I think this can be a solution:

<?php
function string_between_chars($string, $from, $to){
  preg_match("/$from(.*)$to/",$string,$match);
  return $match[1];
}

Use it like this:

$result = string_between_chars($string, '1\. ', '2\. ');

Add a backslash before dots. Dots has special meaning in regular expressions. You can escape it with the backslash.

Lajos Veres
  • 13,595
  • 7
  • 43
  • 56
0

The following regex works:

/\d+\..*?(?=\d+\.|$)/

In PHP:

$str = '1. A post-hardcore band from Brazil 2. A rock band from Sweden' 
         .'3. A rock band from Hawaii 4. A metal band from Germany';
preg_match_all('/\d+\..*?(?=\d+\.|$)/',$str,$matches);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => 1. A post-hardcore band from Brazil 
            [1] => 2. A rock band from Sweden
            [2] => 3. A rock band from Hawaii 
            [3] => 4. A metal band from Germany
        )
)

Working Example

OGHaza
  • 4,795
  • 7
  • 23
  • 29
0

Hi you can simply use this regex as long as no digits in the sentences:

(\d\.\s*[^\d]+)

Demo

But if digits are in the sentences, check @OGHaza's solution instead :)

Enissay
  • 4,969
  • 3
  • 29
  • 56
  • 1
    matching `\s*` is unnecessary, which leaves you with exactly my regex. – OGHaza Nov 17 '13 at 13:00
  • Yes undeed, just in case there's multiple spaces.. who knows :) – Enissay Nov 17 '13 at 13:03
  • Yes but it makes literally no difference to the matches. `.` matches whitespace, so `\s*.*? = .*?` And it is the last thing in the lookahead and the `*` means match whether or not theres whitespace. So it makes 0 difference to any matches. – OGHaza Nov 17 '13 at 13:05
  • Oh damn, I see your point, you're totally right.... – Enissay Nov 17 '13 at 13:07