1

我正在尝试使用简单的 HTML DOM 拆分我从网页中提取的名称,而 list 和 explode 函数并没有起到作用。我想要做的就是取一个名字 {firstname middle(optional) lastname} 并将它们拆分。中间名只出现在一些名字上,如果我能处理好,那将是一个奖励。

这是代码:

    <?php

    $data = new simple_html_dom();  
    $data->load_file("http://www.ratemyprofessors.com/ShowRatings.jsp?tid=861228");
    $profName= $data->find("//*[@id=profName]", 0);
    $profName = strip_tags($profName);
    echo "Full Name: " . $profName = trim($profName);
    list($first, $last) = explode(' ', "$profName ");
    echo "first name: " .  $first;
    echo "last name: " . $last;
?>

我的输出内容如下:

Full Name: Jennifer Aaker
firstname: Jennifer Aaker
lastname: 
4

2 回答 2

3

尝试:

list($first, $last) = explode("&nbsp;", $profName);
于 2012-09-08T21:14:17.077 回答
0

这是一个可以解决问题的简单函数。

function first_last($s) {
    /* assume first name is followed by a whitespace character. take everything after for last. middle initial will be returned as part of last. */
    $pos = strpos($s,' ');
    if ($pos == FALSE) { // if space is not found... call if first name
        return array($s,''); 
    }
    $first = substr($s, 0 , $pos);
    $last = substr($s,$pos + 1);    
    return array($first,$last);
}

// test
$s2 = 'john stewart';
list($first,$last) = first_last($s2);
于 2013-10-07T17:01:35.917 回答