PHP - 格式化字符串

时间:2017-02-10 02:50:15

标签: javascript php jquery

我使用nba.com网站here制作我的每日NBA赛程,但是现在它改变了它的布局,它包含更多数据。使用PHP,我能够转向

这个:

5:00 PM ET
LA Clippers
Charlotte Hornets
Spectrum Center
Charlotte, NC
GAME PREVIEWBUY TICKETS

进入这个:

5:00 PM ET
LA Clippers
Charlotte Hornets

但是,我很难将其转变为:

5:00 PM ET LA Clippers @ Charlotte Hornets

我愿意接受其他语言的建议,比如javascript / jquery,如果不是PHP,我可以将其实现为用户脚本。

有什么建议吗?

我正在使用的代码来清理我不想要的字词。

<?php
$name = $_POST["teamname"];
$words = array("Spectrum Center","Charlotte, NC","Bankers Life Fieldhouse","Indianapolis, IN","Wells Fargo Center","Philadelphia, PA","Quicken Loans Arena","Cleveland, OH","bc","Chesapeake Energy Arena","Oklahoma City, OK","Toyota Center","Houston, TX","American Airlines Center","Dallas, TX","GAME PREVIEWBUY TICKETS","Vivint Smart Home Arena","
Salt Lake City, UT");
$name = str_replace($words,"",$name);

if(isset($_POST["teamname"])){
    echo 'output:<br /><br /><textarea name="teamname" cols="80" rows="20" onclick="this.focus();this.select()">'.$name.'</textarea>';
    }
?>

编辑:添加了我的代码。

1 个答案:

答案 0 :(得分:1)

javascript,您可以在字符串上调用.split("\n"),然后使用Array.prototype.splice()将一个或多个元素添加到数组,然后在数组上调用.join("")以返回字符串。< / p>

let data = `5:00 PM ET
LA Clippers
Charlotte Hornets
Spectrum Center
Charlotte, NC
GAME PREVIEWBUY TICKETS`;

let arr = data.split("\n").slice(0, 3);
arr.splice(-1, 0, " @ ");
arr.splice(1, 0, " ");

console.log(arr.join(""));

在jsfiddle处给定字符串,在行"bc"处省略26,您可以使用do..while循环,将变量递增6以在下一个日期之前跳过三行线。

let data = `5:00 PM ET
LA Clippers
Charlotte Hornets
Spectrum Center
Charlotte, NC
GAME PREVIEWBUY TICKETS
7:00 PM ET
Milwaukee Bucks
Indiana Pacers
Bankers Life Fieldhouse
Indianapolis, IN
GAME PREVIEWBUY TICKETS
7:30 PM ET
Miami Heat
Philadelphia 76ers
Wells Fargo Center
Philadelphia, PA
GAME PREVIEWBUY TICKETS
7:30 PM ET
Denver Nuggets
Cleveland Cavaliers
Quicken Loans Arena
Cleveland, OH
GAME PREVIEWBUY TICKETS
8:30 PM ET
Golden State Warriors
Oklahoma City Thunder
Chesapeake Energy Arena
Oklahoma City, OK
GAME PREVIEWBUY TICKETS
9:00 PM ET
Phoenix Suns
Houston Rockets
Toyota Center
Houston, TX
GAME PREVIEWBUY TICKETS
9:00 PM ET
Orlando Magic
Dallas Mavericks
American Airlines Center
Dallas, TX
GAME PREVIEWBUY TICKETS
10:00 PM ET
Boston Celtics
Utah Jazz
Vivint Smart Home Arena
Salt Lake City, UT`;

let [arr, n, next, res] = [data.split("\n"), 0, 6, Array()];

do {
  let curr = arr.slice(n, n + 3);
  curr.splice(-1, 0, " @ ");
  curr.splice(1, 0, " ");
  res.push(curr.join(""));
  n += next;
} while (n + next < arr.length);

console.log(res);

var text = "";
var i;
for (i = 0; i < res.length; i++) {
    text += res[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
<div id="demo"></div>