将字符串拆分为2个变量...无法正常工作

时间:2012-09-17 17:07:46

标签: php explode

我试图从数据库中取出事件名称(例如:Manny Pacquiao与Juan Manuel Marquez),将事件名称分为2个名字(Manny Pacquiao,Juan Manuel Marquez)并在页面上使用它们。 / p>

这是我的代码无效。

    if(count($perfarray) == 2 && $page['catnum'] == "1142")
    {

        $input = $event['Event'];
        $params = explode('vs.', $input);
        foreach($params as $param) 
            {
                $kv = explode('vs.', $param);
                $fighterNo1 = $kv[0];
                $fighterNo2 = $kv[1];
            }

        $fulltext = str_replace("\$Fighter1", $fighterNo1, $fulltext);
        $fulltext = str_replace("\$Fighter2", $fighterNo2, $fulltext);

        // $fulltext = str_replace("\$Fighter1", addslashes($perfarray[0]), $fulltext);
        //$fulltext = str_replace("\$Fighter2", addslashes($perfarray[1]), $fulltext);
    }
    elseif(strstr($event['Event']," vs."))
    {
        $input = $event['Event'];
        $params = explode('vs.', $input);
        foreach($params as $param) 
            {
                $kv = explode('vs.', $param);
                $fighterNo1 = $kv[0];
                $fighterNo2 = $kv[1];
            }

        $fulltext = str_replace("\$Fighter1", $fighterNo1, $fulltext);
        $fulltext = str_replace("\$Fighter2", $fighterNo2, $fulltext);
    }

3 个答案:

答案 0 :(得分:1)

    $input = $event['Event'];
    $params = explode('vs.', $input);
    foreach($params as $param) 
        {
            $kv = explode('vs.', $param);
            $fighterNo1 = $kv[0];
            $fighterNo2 = $kv[1];
        }

在上面的第二行中,您explode已经$params了吗?在第5行,你再次explode ing?

答案 1 :(得分:1)

你打电话的次数太多了。

$params = explode('vs.', $input);
foreach($params as $param) {
   $kv = explode('vs.', $param);

您正在使用第一个参数,然后再次尝试explode。我认为这应该有效:

$input = $event['Event'];
$params = explode('vs.', $input);
$fighterNo1 = $params[0];
$fighterNo2 = $params[1];

$fulltext = str_replace("\$Fighter1", $fighterNo1, $fulltext);
$fulltext = str_replace("\$Fighter2", $fighterNo2, $fulltext);

答案 2 :(得分:0)

我不确定您的数据究竟如何,但这是您可以做的

$text = "Manny Pacquiao vs. Juan Manuel Marquez";

list($fighter1,$fighter2) =explode(" vs. ",$text);

$fulltext = str_replace("\$Fighter1", $fighter1, $fulltext);
$fulltext = str_replace("\$Fighter2", $fighter2, $fulltext);