如何获得PHP和RegEX中某个字符后的值?

时间:2013-01-09 05:39:43

标签: php regex

如何在字符串中获取某个字符(在我的情况下为'@')之后的值?我有这个代码,但它没有工作; 将只有字母数字字符和/或空格。

$data = 'Someone @Will Be There';

preg_match ("/@([a-zA-Z0-9 ]*)/", $data, $match);
return $match [0];

如果字符串中存在@,我想要得到“Will Be There” 谢谢

修改:非常抱歉我的错误。我不想删除'@',我需要得到什么 After 。再次对不起,人们。

7 个答案:

答案 0 :(得分:1)

更改了我的代码以反映您的更改......

$data = 'Someone @Will Be There';
$character = '@';

if ($string = stringAfterCharacter($data, $character)){
    echo $string;
}else{
    echo "Character: '$character' not found.";
}


function stringAfterCharacter($data, $character='@'){
    if (($pos = strpos($data, $character)) !== false){
        return substr($data, $pos + 1);
    }else{
        return false;
    }
}

答案 1 :(得分:0)

您可以使用函数strpos()来实现此目的。它在字符串中搜索子字符串 - 或者至少是char - 并返回该子字符串的第一个位置。

$position = strpos('I am @ the penthouse', '@');

当在字符串中找不到子字符串时,该方法返回false。

php中有strpos()常见的陷阱。请检查以下示例:

if(!strpos('@stackoverflow', '@')) {
  echo 'the string contains no @';
 }

尽管字符串包含at,但输出'@'未找到。那是因为PHP中的数据类型很弱。之前的strpos()调用将返回int(0),因为它是字符串中的第一个char。但是除非你这样做,否则这将使if失败:

if(strpos('@stackoverflow', '@') === FALSE) {
   echo 'the string contains no @';
}

答案 2 :(得分:0)

最好能使用简单的字符串替换方法并试试这个,

$data = 'Someone @Will Be There';
$result = str_replace('@','',$data); // result is: Someone Will Be There

不要使用:

//preg_match ("/@([a-zA-Z0-9]*)/", $data, $match);
//return $match [0];

答案 3 :(得分:0)

你不需要使用通常很慢的正则表达式来做到这一点。做就是了: return str_replace('@','',$ data);

答案 4 :(得分:0)

这将删除字符串中的所有符号

$data = 'Someone @Will Be There';
echo preg_replace("/([^A-Za-z0-9 ]*)/", '', $data); //Add character in the pattern if not to be filtered

<强>输出:

Someone Will Be There

答案 5 :(得分:0)

你的问题似乎含糊不清,如果你想从字符串中删除'@',那么你可以使用str_replace的答案。 如果你想要'@'之后的值,你应该在你自己的代码中检查$ match [1]。

答案 6 :(得分:0)

第一组位于$match[1],而不是$match[0]

将您的代码更改为:

$data = 'Someone @Will Be There';
preg_match ("/@([a-zA-Z0-9 ]*)/", $data, $match);
return $match[1];