在PHP中获取特定字符后的单词

时间:2014-12-08 10:54:29

标签: php

我希望将字符串放在特定字符之前的字符串中,在本例中为:字符。

  

textexjkladjladf:theword texttextext:otherword:anotherword

从这个片段中,预期的输出将是:

  • theword
  • otherword
  • anotherword

我如何使用PHP?

3 个答案:

答案 0 :(得分:3)

您可以使用正则表达式:

$string = "textexjkladjladf :theword texttextext :otherword :anotherword";
$matches = array();
preg_match_all('/(?<=:)\w+/', $string, $matches);
foreach ($matches[0] as $item) {
    echo $item."<br />";
}

输出是:

theword
otherword
anotherword

您想要的数组是$matches[0]

答案 1 :(得分:1)

获得没有正则表达式的单词的另一种方法是:

使用explode(&#39;&#39;,$ str)获取所有单词。

然后循环单词并检查哪一个以&#39;:&#39;。

开始。

答案 2 :(得分:-1)

尝试

$str = 'textexjkladjladf :theword texttextext :otherword :anotherword';
$tab = exlode(':',$str);
print_r($tab);
//if echo entry 0 =>
echo $tab[0]; // => textexjkladjladf