如何在某些字符串行之前或之后添加单词

时间:2014-01-20 10:38:29

标签: php http

使用PHP,我有一个名单列表,我想在每行的第一行添加:

'http://

将这一个添加到每行的最后一行:

' , 

示例>>

我有这个:

john
michel 
hosein
ali

我想要这个:

'http://john' , 
'http://michel ' , 
'http://hosein' , 
'http://ali' , 

有没有代码可以帮我吗?

4 个答案:

答案 0 :(得分:4)

如果您的行在数组中,您可以使用以下内容:

$out = array_map(function($item) {
    return "'http://{$item}', ";
}, $data);

如果它们不是你必须使用explode(或preg_split)将它们放入数组

答案 1 :(得分:2)

我希望这段代码有用:

<?
$lineStart= "'http://";
$lineEnd  = "' , ";
$names    = array("john", "michel", "hosein", "ali"); //array with names

for ($i=0; $i<count($names) ; $i++)                  //echo as many times as the number of names in a string
{
    echo $lineStart.$names[$i].$lineEnd."<br>";      //just string concatenation
}
?>

答案 2 :(得分:1)

例如,您的值位于名为$array的数组中,并且您希望将新格式保存在名为$new_array的数组中,您可以尝试这样:

$new_array = array();
foreach($array as $value) {
    $new_array[] = "'http://".$value."' ,";
}

答案 3 :(得分:1)

<?php
    $ary = array("john", "michel", "hosein", "ali");
    $newArray = array();

    foreach($ary as $val) 
        $newArray[] = "'http://" .$val. "', ";
?>

要从文件中获取名称列表,

编辑:

<?php
    $ary = file("inputfile.txt", FILE_IGNORE_NEW_LINES);
    $newArray = array();

    foreach($ary as $val) {
        $newArray[] = "'http://".$val."', ";
    }
?>

此处, inputfile.txt 逐行包含名称。

离。

john
michel 
hosein
ali
相关问题