user3142695
user3142695

Reputation: 17362

Check if string in string and extract it

I got a string which may have 1-3 stars at the beginning. I want to check if there are stars and if this is the case, I need to extract them as a integer.

* Lorem ipsum
** Lorem ipsum
*** Lorem ipsum
Lorem ipsum

Result:

array(1, 'Lorem ipsum')
array(2, 'Lorem ipsum')
array(3, 'Lorem ipsum')
array(0, 'Lorem ipsum')

Upvotes: 1

Views: 51

Answers (2)

Amal
Amal

Reputation: 76646

You can use preg_match_all():

$text = <<<TEXT
* Lorem ipsum
** Lorem ipsum
*** Lorem ipsum
Lorem ipsum
TEXT;

preg_match_all('/^(\**)\s*(.*)$/m', $text, $matches);
list(, $keys, $values) = $matches;

for ($i=0; $i < count($keys); $i++) 
    $result[] = [strlen($keys[$i]), $values[$i]];

var_export($result);

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => Lorem ipsum
        )

    [1] => Array
        (
            [0] => 2
            [1] => Lorem ipsum
        )

    [2] => Array
        (
            [0] => 3
            [1] => Lorem ipsum
        )

    [3] => Array
        (
            [0] => 0
            [1] => Lorem ipsum
        )

)

Upvotes: 1

anubhava
anubhava

Reputation: 786101

You can use:

$s = '*** Lorem ipsum';

if (preg_match('/^(\**) *(.+)$/', $s, $m)) {
    $out = array(strlen($m[1]), $m[2]);
    print_r($out);
}

Output:

array(
  0 => 3,
  1 => "Lorem ipsum",
)

Upvotes: 1

Related Questions