1

I want to find anything that matches

[^1] and [/^1]

Eg if the subject is like this

sometext[^1]abcdef[/^1]somemoretext[^2]12345[/^2]

I want to get back an array with abcdef and 12345 as the elements.

I read this

And I wrote this code and I am unable to advance past searching between []

<?php


$test = '[12345]';

getnumberfromstring($test);

function getnumberfromstring($text)
{
    $pattern= '~(?<=\[)(.*?)(?=\])~';
    $matches= array();
    preg_match($pattern, $text, $matches);

    var_dump($matches);
}

?>
Community
  • 1
  • 1
Kim Stacks
  • 10,202
  • 35
  • 151
  • 282

3 Answers3

1

Your test checks the string '[12345]' which does not apply for the rule of having an "opening" of [^digit] and a "closing" of [\^digit]. Also, you're using preg_match when you should be using: preg_match_all

Try this:

<?php


$test = 'sometext[^1]abcdef[/^1]somemoretext[^2]12345[/^2]';

getnumberfromstring($test);

function getnumberfromstring($text)
{
    $pattern= '/(?<=\[\^\d\])(.*?)(?=\[\/\^\d\])/';
    $matches= array();
    preg_match_all($pattern, $text, $matches);

    var_dump($matches);
}

?>
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
1

That other answer doesn't really apply to your case; your delimiters are more complex and you have to use part of the opening delimiter to match the closing one. Also, unless the numbers inside the tags are limited to one digit, you can't use a lookbehind to match the first one. You have to match the tags in the normal way and use a capturing group to extract the content. (Which is how I would have done it anyway. Lookbehind should never be the first tool you reach for.)

'~\[\^(\d+)\](.*?)\[/\^\1\]~'

The number from the opening delimiter is captured in the first group and the backreference \1 matches the same number, thus insuring that the delimiters are correctly paired. The text between the delimiters is captured in group #2.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
0

I have tested following code in php 5.4.5:

<?php
$foo = 'sometext[^1]abcdef[/^1]somemoretext[^2]12345[/^2]';    
function getnumberfromstring($text)
{    
    $matches= array();
    # match [^1]...[/^1], [^2]...[/^2]
    preg_match_all('/\[\^(\d+)\]([^\[\]]+)\[\/\^\1\]/', $text, $matches, PREG_SET_ORDER);    
    for($i = 0; $i < count($matches); ++$i)
        printf("%s\n", $matches[$i][2]);
}
getnumberfromstring($foo);

?>

output:

abcdef
123456
godspeedlee
  • 672
  • 3
  • 7