Home > Enterprise >  How to get last strings starts with '@' and numbers in PHP?
How to get last strings starts with '@' and numbers in PHP?

Time:10-19

I need to extract all whitespace separated "words" at the end of string that either start with the @ character or that consist solely of digits.

For example, I have this string:

hello @tag1 111 world @tag2 @tag3 222 333

I need to obtain

@tag2 @tag3 222 333

I have used this code below:

preg_match_all('~\B@\S |\b\d \b~', $string, $match);

With this, I'll get all strings that started with '@' character and numbers, even @tag1 and 111.

I also tried the code below:

$str = 'hello @tag1 111 world @tag2 @tag3 222 333';
$exp = explode(' ', $str);
$arraysfordelete = [];
foreach ($exp as $num => $user) {
    if (!preg_match('~\B@\S |\b\d \b~', $user, $match)) {
        array_push($arraysfordelete, $num);
    }
}
$array = array_slice($exp, end($arraysfordelete)   1);
echo implode(' ', $array);

Any suggestions?

CodePudding user response:

You could use, for example

~[@\d]\S ~

which means match a @ or a digit, followed by one or more non-space characters \S .

Or

~(?<!\S)[@\d]\S ~

if you want to make sure there is no non-space character preceding the @ or digit.

CodePudding user response:

Here is the PHP solution you need:

$str = 'hello @tag1 111 world @tag2 @tag3 222 333';
if (preg_match('~(?<!\S)(@\S |\d )(?:\s (?1))*(?=\s*$)~', $str, $m)) {
    echo $m[0];
}
// => @tag2 @tag3 222 333

See the regex demo. Details:

  • (?<!\S) - a location that is either right after a whitespace or start of string
  • (@\S |\d ) - Group 1: @ and one or more non-whitespace chars or one or more digits
  • (?:\s (?1))* - zero or more occurrences of one or more whitespaces and then Group 1 pattern
  • (?=\s*$) - immediately to the right, there must be zero or more whitespaces and end of string.
  • Related