1

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')

2 Answers 2

1

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",
)
Sign up to request clarification or add additional context in comments.

Comments

1

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
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.