开发者

PHP preg_match tag + curly braces

开发者 https://www.devze.com 2023-02-23 08:41 出处:网络
I have a string such as: #sometag-{serialized-data-here} And I want to match this pattern, but use everything inside the curly braces (so I can unserialize it later). How can I match this text patt

I have a string such as:

#sometag-{serialized-data-here}

And I want to match this pattern, but use everything inside the curly braces (so I can unserialize it later). How can I match this text pattern with preg_match()?

So far I have:

preg_match('~{[^{}]*}~', $text, $match);

but this just matches the contents of the braces if in $text without the hash tag.

EDIT: Here is the logic of what im trying to accomplish:

  $user_post = "Here is my cool post that contains some media.";
  $media = array("mediatype" => "sometype", "id" => "ebJ2brErERQ", "title" => "Some cool video", "description" => "Some cool description");  
  $user_post .= "#sometag-" . serialize($media);

Later, when I fetch $user_post from the database, I want to ma开发者_如何学Gotch the text, strip it out and display the media.

I'll have something like this:

Here is my cool post that contains some media.#sometag-a:4:{s:9:"mediatype";s:8:"sometype";s:2:"id";s:11:"ebJ2brErERQ";s:5:"title";s:15:"Some cool video";s:11:"description";s:21:"Some cool description";}


Why not use explode()?

$tag_data_arr = explode('-', $text, 2);


Make it greedy...

$text = "#sometag-{hello:{}{}yooohooo}";

preg_match('/#([\w]+)\-{(.*)}/is', $text, $matches);

print_r($matches);

Result...

Array
(
    [0] => #sometag-{hello:{}{}yooohooo} //everything
    [1] => sometag //tag
    [2] => hello:{}{}yooohooo //serialized data
)


Use this:

preg_match('~#sometag-({[^{}]*})~', $text, $match);

Then:

echo $match[1];

To be a little more specific, () defines subpatterns. You can use as many as you want to match different things in a regular expression. Per example:

preg_match('~#(some)(tag)-({[^{}]*})~', $text, $match);
echo $match[1]; // some
echo $match[2]; // tag
echo $match[3]; // {serialized-data-here}

Note: You want want to use preg_match_all instead.

0

精彩评论

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