PHP preg_match函数变量提取

发布于 2024-12-20 18:53:50 字数 246 浏览 2 评论 0原文

假设我有一个像这样的字符串:

[$IMAGE[file_name|width|height]]

How can I match and getting 2 variables

$tag = "IMAGE"
$param = "file_name|width|height"

using a php preg_match function?

Assuming that I have a string like this:

[$IMAGE[file_name|width|height]]

How can I match and obtain 2 variables

$tag = "IMAGE"
$param = "file_name|width|height"

Using a php preg_match function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌化 2024-12-27 18:53:50
$string = '[$IMAGE[file_name|width|height]]';
// Matches only uppercase & underscore in the first component
// Matches lowercase, underscore, pipe in second component
$pattern = '/\[\$([A-Z_]+)\[([a-z_|]+)\]\]/';
preg_match($pattern, $string, $matches);

var_dump($matches);
array(3) {
  [0]=>
  string(32) "[$IMAGE[file_name|width|height]]"
  [1]=>
  string(5) "IMAGE"
  [2]=>
  string(22) "file_name|width|height"
}
$string = '[$IMAGE[file_name|width|height]]';
// Matches only uppercase & underscore in the first component
// Matches lowercase, underscore, pipe in second component
$pattern = '/\[\$([A-Z_]+)\[([a-z_|]+)\]\]/';
preg_match($pattern, $string, $matches);

var_dump($matches);
array(3) {
  [0]=>
  string(32) "[$IMAGE[file_name|width|height]]"
  [1]=>
  string(5) "IMAGE"
  [2]=>
  string(22) "file_name|width|height"
}
长发绾君心 2024-12-27 18:53:50

不使用 preg_match,但效果也一样。

$var = '[$IMAGE[file_name|width|height]]';
$p1 = explode('[',$var);
$tag = str_replace('
,'',$p1[1]);
$param = str_replace(']','',$p1[2]);

echo $tag.'<br />';
echo $param;

Doesn't use preg_match, but works just as well.

$var = '[$IMAGE[file_name|width|height]]';
$p1 = explode('[',$var);
$tag = str_replace('
,'',$p1[1]);
$param = str_replace(']','',$p1[2]);

echo $tag.'<br />';
echo $param;
辞取 2024-12-27 18:53:50
<?php
$string = '[$IMAGE[file_name|width|height]]';
preg_match("/\[\\$(.*)\[(.*)\]\]/",$string,$matches);

$tag = $matches[1];  
$param = $matches[2];

echo "TAG: " . $tag;
echo "<br />";
echo "PARAM: " . $param;
?>
<?php
$string = '[$IMAGE[file_name|width|height]]';
preg_match("/\[\\$(.*)\[(.*)\]\]/",$string,$matches);

$tag = $matches[1];  
$param = $matches[2];

echo "TAG: " . $tag;
echo "<br />";
echo "PARAM: " . $param;
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文