如何拆分在一场比赛中分开的字符串

时间:2014-04-15 18:43:18

标签: php string

我正在使用我的PHP解析内容,因为我正在使用simple_html_dom。我想在时间和节目标题之间拆分字符串。

这是字符串:

2:00 PM                                               Local Programming

我想将字符串分开以使它像这样:

<span id="time1">2:00 PM </span> - <span id="title1">Local Programming</span>

这是PHP:

<?php
$links = $row['links'];
$html = file_get_html($links);

$base = $row['links'];

$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_URL, $base);
curl_setopt($curl, CURLOPT_REFERER, $base);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$str = curl_exec($curl);
curl_close($curl);

// Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($str);

if ($html->find('li[id=row1-24]', 0) == True)
{
  $title1 = $html->find('li[id=row1-24]', 0)->plaintext; // with this
}

echo $title1;
?>

您能否告诉我如何将字符串拆分为两个不同的变量,以便我可以在PHP中输出它们?

2 个答案:

答案 0 :(得分:0)

这个怎么样?

$title1 = preg_split("/ {4,}/",$title1);
echo '<span id="time1">' . $title1[0] . '</span> - <span id="title1">' . $title1[1] . '</span>';

这会将字符串拆分为四个或更多空格中的数组。

返回的数组中有两个项目,如下所示:["2:00 PM","Local Programming"]

然后它使用数组创建所需的HTML标记并echo s。

答案 1 :(得分:0)

使用正则表达式可以执行以下操作:

// using regex grab the time and title separately
preg_match('/(\d{1,2}:\d{2}\s?\w{2})\s+([\w\s\d]+)', trim($title1), $matches);

// matches[1] is the time and matches[2] is the title
echo "<span id=\"time1\">$matches[1]</span> - <span id=\"title1\">$matches[2]</span>";