开发者

Grabbing a word from a character?

I have don开发者_开发问答e my google research. I've tried preg_match, strsub_replace, almost everything.

I honestly can't seem to figure out how to grab a word that is connected to a character.

I have a statuses system on my website. I am trying to figure out how replace a word with something else if it has the character '@' in it.. like on twitter, when you say '@person'.

Any help is very much appreciated.


to just print matches:

preg_match_all("/@([0-9a-z]+)/i",$input,$matches);
print_r($matches[1]);

to replace them:

$input = preg_replace('/@([0-9a-z]+)/i','-->\1<--',$input);

will replace @text with -->text<--, as an example.


All answers are good if you try to match , if you try to replace here is how i would do it:

$string = "some text @person some other text 
 some @pers
 @pess text";
var_dump(preg_replace('/@.*\s/i', '#replacement#', $string));

Where "#replacement#" is the string that replaces all words starting with "@" and ending with a space.


Edit , to get the code working in all case ( don't replace emails , don't replace whitespaces as pointed by @mvdc , replace words that start with "special characters" , using U as stated by @mvdc ) This should work in desired cases .

$string = "some text @person some other text\n
 some @pers\n
 @pess text email@google.com the email should not be replaced ,\n
 @!11@21ss should be replaced , whitespaces not and \\n not";
var_dump(preg_replace('/\s\@.*\s/U', ' #replacement# ', $string));
exit;

Edit , 4'th revision

  $string = "@sasa32@ some text @person some other text@3232##!@ this can pass as an email
 some @pers\n
 @pess text email@google.com the email should not be replaced ,\n
 @!11@21ss should be replaced , whitespaces not and \\n not @poelinca!";
var_dump(preg_replace('/(\s|^|\A)\@.*(\s|\Z|$)/U', ' #replacement# ', $string));
exit;


I'd recommend RegexPal for helping you figure out expressions. Interpreting your questions your want to find an element that starts with an "@" followed by characters ...

<?php

$isMatches =preg_match_all("/^@.+$/", $stringToSearch, $matches);

?>

Would match all templates in a string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜