开发者

PHP: Find and exctract into an array all instances of specific text in a string

I have a string that contains several "placeholders" in it, and each placeholder is marked with this syntax: {value}.

I want to be able to pull out each placeholder within the string and load them into an array.

For example, if I had this string here... "this is a {test} string, to demonstrate my {objective}."

I would wa开发者_StackOverflownt the end result to be an array that contained two values, "test" and "objective".

I poked around with preg_split but couldn't quite wrap my head around it. Any ideas on how to make this happen?

Thanks!


You can try the following to get what you need:

$placeHolders = array();
if(preg_match_all('/\{([^{}}]+)\}/', $haystack, $matches)) {
    $placeHolders = $matches[1];
}

Since you didn't specifically state what would be allowed in a place holder, I kept the regular expression quite generic. Basically, a placeholder would be anything inside curly braces (except for curly braces themselves).

You might want to restrict more, such as alphanumeric characters only. In this case try:

'/\{([a-zA-Z0-9]+)\}/'

Edit: a resource for regular expressions: http://www.regular-expressions.info/reference.html


I think you can use this

preg_match_all('/\{([^\}]+)\}/i', $your_string, $match);

all the placeholders in $match[1]; Read more about that function at http://php.net/manual/en/function.preg-match-all.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜