Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to get last strings starts with '@' and numbers in PHP?

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!