codeworxx
codeworxx

Reputation: 310

preg_match all words start with an @?

i'm not very firm with regular Expressions, so i have to ask you:

How to find out with PHP if a string contains a word starting with @ ??

e.g. i have a string like "This is for @codeworxx" ???

I'm so sorry, but i have NO starting point for that :(

Hope you can help.

Thanks, Sascha


okay thanks for the results - but i did a mistake - how to implement in eregi_replace ???

$text = eregi_replace('/\B@[^\B]+/','<a href="\\1">\\1</a>', $text);

does not work??!?

why? do i not have to enter the same expression as pattern?

Upvotes: 1

Views: 7302

Answers (5)

CaptainStiggz
CaptainStiggz

Reputation: 1897

Just incase this is helpful to someone in the future

/((?<!\S)@\w+(?!\S))/

This will match any word containing alphanumeric characters, starting with "@." It will not match words with "@" anywhere but the start of the word.

Matching cases:

@username
foo @username bar
foo @username1 bar @username2

Failing cases:

foo@username
@username$
@@username

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342383

@OP, no need regex. Just PHP string methods

$mystr='This is for @codeworxx';
$str = explode(" ",$mystr);
foreach($str as $k=>$word){
    if(substr($word,0,1)=="@"){
        print $word;
    }
}

Upvotes: 0

Amirshk
Amirshk

Reputation: 8258

Assuming you define a word a sequence of letters with no white spaces between them, then this should be a good starting point for you:

$subject = "This is for @codeworxx";
$pattern = '/\s*@(.+?)\s/';
preg_match($pattern, $subject, $matches);
print_r($matches);

Explanation: \s*@(.+?)\s - look for anything starting with @, group all the following letters, numbers, and anything which is not a whitespace (space, tab, newline), till the closest whitespace.

See the output of the $matches array for accessing the inner groups and the regex results.

Upvotes: 1

miku
miku

Reputation: 188034

Match anything with has some whitespace in front of a @ followed by something else than whitespace:

$ cat 1812901.php

<?php
    echo preg_match("/\B@[^\B]+/", "This should @match it");
    echo preg_match("/\B@[^\B]+/", "This should not@ match");
    echo preg_match("/\B@[^\B]+/", "This should match nothing and return 0");
    echo "\n";
?>

$ php 1812901.php 
100

Upvotes: 5

Pieter888
Pieter888

Reputation: 4992

break your string up like this:

$string = 'simple sentence with five words';
$words = explode(' ', $string );

Then you can loop trough the array and check if the first character of each word equals "@":

if ($stringInTheArray[0] == "@")

Upvotes: 1

Related Questions