2013-10-15 98 views
1

我需要一些帮助,使我的2-3代码折磨的PHP代码。 Ny方法尝试但没有结果。我想借此@后的第一个和第二个字,例如@约翰母鹿和PHP的结果却让我约翰和李四PHP获得第一个和第二个词后(在)

我一点东西: (编辑)

$q = 'Hi @Stefan Simeonov kak si? @Krasi avramov'; 
    if (preg_match_all("(@[^ ]+[ ][^ ]+)", $q, $match)) { 
     foreach ($match[0] as $singleMatch) { 
      $finded[] = $singleMatch; 
      $success = 1; 
     } 
    } elseif (preg_match_all("(@[^ ]+)", $q, $match)) { 
     foreach ($match[0] as $singleMatch) { 
      $finded[] = $singleMatch; 
      $success = 1; 
     } 
    } else { 
     $success = 0; 
    } 

    if($success = 1) { 
     $replace = $q; 
     foreach ($finded as $user) { 
      $expl = explode("@",$user); 
      $rep = '<a href="?profile='.$expl[1].'">'.$expl[1].'</a>'; 
      $replace = str_replace($user,$rep,$replace); 
     } 
     echo $replace; 
    } else { 
     echo $q; 
    } 
+1

您需要添加一些代码,指出您可能出错的地方以及您期望的结果。 – mavrosxristoforos

+0

http://regular-expressions.info/tutorial.html – deceze

+0

在一个字符串中可以有多个@ ...吗? –

回答

1

你可以做是这样的:

<? 
$q = 'Hi @John Doe kak si?'; 
$explodeTab = explode("@",$q); 
$words = explode(" ",$explodeTab[1]); 
print_r($words); 
?> 

WORKING CODE

+1

这是最好的方法 –

0

您可以使用(@[^ ]+[ ][^ ]+)一个正则表达式是:

<?php 
    $q = 'Hi @Stefan Simeonov kak si?'; 
    if (preg_match_all("(@[^ ]+[ ][^ ]+)", $q, $match)) { 
     foreach ($match[0] as $singleMatch) { 
      echo 'Found match: ' . $singleMatch . PHP_EOL; 
     } 
    } 
?> 

将输出:

找到匹配:@Stefan Simeonov

+0

谢谢!它的作品:)) –

+0

''''→只是一个空间;不需要为单个字符创建一个字符组。 – deceze

+0

@deceze我知道 - 这对我来说是纯可读性*。这样我可以浏览代码并知道我是故意做到的。 – h2ooooooo

3

使用正则表达式,例如:

<?php 
$q = 'Hi @John Doe kak si?'; 

if (preg_match('/@(\w+)\s(\w+)/', $q, $matches)) { 
    var_dump($matches); 
} 

这将在后寻找一个单词,后跟一个空格,然后是另一个单词。

+0

这个输出:Array([0] => @John Doe [1] => John [2] => Doe) 我不确定OP是否希望在输出中有@。 – Adam

+0

@Adam然后OP只需要使用'$ matches [1]'和'$ matches [2]'。 – deceze

0

假设单词总是由空格分隔,可以通过首先分割@字符上的输入字符串,然后获取第1项并将其分割为空格字符并将结果减少为所需单词。

<?php 
$q = 'Hi @John Doe kak si?'; 
$atSplitResult = explode('@', $q); 
$spaceSplitResult = explode(' ', $atSplitResult[1]); 
$firstTwoWords = array_slice($spaceSplitResult, 0, 2); 

var_dump($firstTwoWords); 
0

比方说,我们有一个句子

让我们来看看,@mike,你怎么做?

现在:

$atExploded = explode('@', $str); //where $str is our string 
if(count($atExploded)){ 
    foreach($atExploded as $at){ 
    $spaceExplode = explode(' ', $at); 
    echo $spaceExplode[0].' '.$spaceExplode[1]; //after checking that [0] and [1] are reachable 
    } 
} 

当然,你应该减少任何不必要的字符(如括号,冒号等),但我希望你的想法。

0

PHP

$string = 'Hi @John Doe kak si?'; 
$regex = preg_match("/@(.+?)\s(.+?)\s/", $string, $matches); 
var_dump($matches); 

返回

array(3) { [0]=> string(10) "@John Doe " [1]=> string(4) "John" [2]=> string(3) "Doe" } 
0

你可以写这样的事情。这将输出@John Doe

<?php 
$q = 'Hi @John Doe kak si?'; 
$q = preg_match('/@[A-Za-z]+\s[A-Za-z]+/', $q, $match); 
print_r($match); 

?> 
相关问题