简体   繁体   English

PHP正则表达式,提取指定字符之间的字符

[英]PHP regex, extracting characters between specified characters

I cannot for the life of me seem to be able to figure out how I extract characters between characters. 我一生似乎无法弄清楚如何在字符之间提取字符。

Consider this string, 考虑这个字符串,

  $string = "sometext/#a=10/#b=25/moretext";

What I would like to do is extract the values of "a" and "b" (10 and 25) 我想做的是提取“ a”和“ b”的值(10和25)

So essentially what I want to do is find "#a=" and grab everything before the following /, then do the same for b. 因此,基本上我想做的就是找到“#a =”并抓取以下/之前的所有内容,然后对b执行相同的操作。 Can anyone tell me how this can be accomplished? 谁能告诉我如何做到这一点?

Also if anyone knows any solid regex tutorials they can recommend I'd very much appreciate it, I've checked nettuts, w3schools, and php.net which all have good ones but any other recommendations would be great. 另外,如果有人知道任何可靠的正则表达式教程,他们可以推荐我,我将非常感激,我已经检查了nettuts,w3schools和php.net,它们都有不错的选择,但是任何其他建议都将是很棒的。 Thank you. 谢谢。

This works for me: 这对我有用:

<?php

$string = "sometext/#a=10/#b=25/moretext/#varname=Hello World/evenmoretext/";

$matchcount = preg_match_all('@#([^=]+)=([^/]*)/@', $string, $matches);

for ($i = 0; $i < $matchcount; ++$i) {
    echo "{$matches[1][$i]} = {$matches[2][$i]}\n";
}

Output: 输出:

a = 10 a = 10
b = 25 b = 25
varname = Hello World varname = Hello World

A long time ago I found the site http://www.regular-expressions.info/ to be helpful and it had good information. 很久以前,我发现该网站http://www.regular-expressions.info/是有用的,并且具有很好的信息。 You may find that a GUI program for testing regular expressions can be helpful as they can show matches in real time as you type an expression. 您可能会发现,用于测试正则表达式的GUI程序可能会有所帮助,因为它们可以在您键入表达式时实时显示匹配项。 An example that comes to mind is Regex Buddy, but this costs money. 想到的一个例子是Regex Buddy,但这要花钱。 This online regex tester looked pretty promising as well. 这个在线正则表达式测试器看起来也很有前途。

$string = "sometext/#a=10/#b=25/moretext";
$expr = '@#([a-z]+)=(.+?)/@';
$count = preg_match_all($expr, $string, $matches);

$result = array();
for ($i = 0; $i < $count; $i++) {
    $result[$matches[1][$i]] = $matches[2][$i];
}

echo "<pre>";
print_r($result);
echo "</pre>";

See it working 看到它正常工作

If you really want to get to grips with the nuts and bolts of regex, the best resource I can recommend is http://www.regular-expressions.info/ 如果您真的想掌握正则表达式的细节,我可以推荐的最佳资源是http://www.regular-expressions.info/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM