0

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:

$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

twinsmaj
  • 55
  • 7
  • Please share your attempt and explain exactly how it failed to do what you need. Side note: you can always test your regex in an online service such as [regex101](https://regex101.com/) - you will find that it has a detailed explanation (step by step) of what it's trying to match. It can help you identify where you went wrong with your pattern. – El_Vanja Apr 29 '21 at 12:57
  • Also, this [very similar question](https://stackoverflow.com/questions/2034687/regex-get-string-value-between-two-characters) should be of help. – El_Vanja Apr 29 '21 at 13:21
  • I also noticed you say you want to match between `#` and `/` (forward slash), but your text has that value between `#` and ``\`` (backslash). – El_Vanja Apr 29 '21 at 13:32
  • You want `row\"> – user3783243 Apr 29 '21 at 17:48
  • Apparently there's been a mistake all along. What I wanted to match all along is any character between '#` and `"` not `\\` (backward slash) which is just an escape character in php. This has been an oversight all along. I finally used this pattern: ```"/#(.*?)\"/s"``` and it worked well. Thanks a lot for the replies – twinsmaj Apr 30 '21 at 04:51

1 Answers1

0

try this pattern - "/(#).?\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.

iZooGooD
  • 37
  • 6