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

时间:2021-04-29 12:55:19

标签: php regex

我对正则表达式很不满意,需要一些帮助来解决以下情况: 如何使用 PHP 提取以下字符串中 #/ 之间的所有字符串:

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

这是我尝试过的,但它几乎只返回一个匹配以及 #/,但我不想要带有字符的结果

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

结果:

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

提前致谢

1 个答案:

答案 0 :(得分:0)

试试这个模式 - "/(#).?\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 />";
}

完成。

相关问题