0

I'm working with CommonMark and I've created a '@mention' parser that will return a link when an @mention is found. However, I'm tweaking it to link full names instead of usernames. Here's what I currently have:

$cursor->match('/^\w+,(.*)\s/');

However, this seems to capture the name incorrectly, and links the start of the other name (see below):

enter image description here

Does anyone have any ideas what I could change to match an entire name separated with a comma and/or space? I'm awful at writing regex.

Thanks for any help in advance!

Edit:

Here's what should match:

(A name can only be 2 words minimum and 3 words maximum)

  • Bauman, Steve
  • Steve Bauman
  • Doe, Mary Sue
  • Mary Sue Doe

A last name with a comma will only be one word.

What should not match:

  • Steve
  • Bauman
  • Mary
  • Doe

The regex needs to match an entire name, not single names.

This is the CommonMark code behind the match method:

if (!preg_match($regex, $subject, $matches, PREG_OFFSET_CAPTURE)) {
    return;
}

This results to:

if (!preg_match('/^\w+,(.*)\s/', "Bauman, Steve", $matches, PREG_OFFSET_CAPTURE)) {
    return;
}
Steve Bauman
  • 8,165
  • 7
  • 40
  • 56

2 Answers2

3

As per your new rules, match a name that has 2 or 3 words and should be separated by spaces ( ) or commas (,)

/\w+([, ]+\w+){1,2}/

Regex 101

degant
  • 4,861
  • 1
  • 17
  • 29
0

Here you go

<?php
$string = <<<EOS
something @name, bla bla bla @name.surname something else
Lorem ipsum @o'brien 
EOS;

$matches = [];
preg_match_all('/@[^\s,]+/', $string, $matches);
var_dump($matches);

and working demo

motanelu
  • 3,945
  • 1
  • 14
  • 21
  • Unforuntately this doesn't work, for example inserting '@Bauman, Steve' results to an array containing "@Bauman" and not "@Bauman, Steve" – Steve Bauman May 04 '17 at 19:21