简体   繁体   English

匹配特定字符之间的字符串

[英]Match string between specific characters

I'm pretty bad with regex and need some help with the scenario below: How do I extract all the strings between # and / in the string below using PHP:我对正则表达式很不好,需要以下场景的帮助:如何使用 PHP 在下面的字符串中提取#/之间的所有字符串:

$text = '<a href=\"http://example.com/what-is-row#row\"><a href=\"http://example.com/what-is-code#code\">';

Here's what I tried but it pretty much returns only one match along with the # and / but I don't want the results with the characters这是我尝试过的,但它几乎只返回一个匹配以及#/但我不想要带有字符的结果

$pattern = "/#(.*?)\//i";
preg_match_all($pattern, $input, $matches);

Result:结果:

array(2) { [0]=> array(1) { [0]=> string(23) "#row\"> array(1) { [0]=> string(21) "row\">

Thanks in advance提前致谢

try this pattern - "/(#). ?\w /"试试这个模式 - "/(#). ?\w /"

$text = '<a href=\"http://example.com/what-is-row#row\"><a href=\"http://example.com/what-is-code#code\">';
$pattern = "/(#).*?\w*/";

preg_match_all($pattern, $text, $matches);

/* 
$matches[0] will have 
#row
#code
now we just need to replace # with "" blank char
the below logic will do it
*/
foreach ($matches[0] as $match) {
  echo str_replace("#","",$match)."<br />";
}

Done.完毕。

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

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