返回两个字符串之间的值

I know this may be a common question but I can't find the exact answer I want.

I have the following string.

#|First Name|#
Random Text
#|Last Name|#

What I would like to do is have all the values that are in between the #| & |# and replace the whole string with a value. This must be in an array so I can loop through them all.

So as an example I have:

#|First Name|#

After processing I would like it to be:

John

So the main logic would be to use the First Name value to print out a value from a database.

Can someone help me out here.

This is code I've tried:

preg_match('/#|(.*)|#/i', $html, $ret);

Thanks

You'll need preg_replace_callback() for this, in addition to making your regex non-greedy and escaping the vertical bar:

$replacements = array( 'John', 'Smith');
$index = 0;
$output = preg_replace_callback('/#\|(.*?)\|#/i', function( $match) use ($replacements, &$index) {
    return $replacements[$index++];    
}, $input);

This will output:

string(24) "John
Random Text
Smith"
$string = '#|First Name|#
Random Text
#|Last Name|#';
$search = array(
    '#|First Name|#',
    '#|Last Name|#',
);
$replace = array(
    'John',
    'Smith',
);
$string = str_replace($search, $replace, $string);