我是php的初学者,我有这样的字符串:
$test = http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
我想将字符串拆分为数组:
Array(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
我该怎么办?
答案 0 :(得分:5)
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg';
$testurls = explode('http://',$test);
foreach ($testurls as $testurl) {
if (strlen($testurl)) // because the first item in the array is an empty string
$urls[] = 'http://'. $testurl;
}
print_r($urls);
答案 1 :(得分:4)
您要求使用正则表达式解决方案,所以在这里...
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
preg_match_all('/(http:\/\/.+?\.jpg)/',$test,$matches);
print_r($matches[0]);
该表达式查找以http://
开头并以.jpg
结尾的字符串部分,其间包含任何内容。这会完全按照要求拆分您的字符串。
输出:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
答案 2 :(得分:1)
如果它们总是像这个vith substr()函数引用那样你可以拆分它们:http://php.net/manual/en/function.substr.php但是如果它们在长度上是动态的。您需要在第二个“http://”之前获得;
或其他任何不太可能使用的符号,然后使用explode函数参考:http://php.net/manual/en/function.explode.php
$string = "http://something.com/;http://something2.com"; $a = explode(";",$string);
答案 3 :(得分:1)
尝试以下方法:
<?php
$temp = explode('http://', $test);
foreach($temp as $url) {
$urls[] = 'http://' . $url;
}
print_r($urls);
?>
答案 4 :(得分:1)
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jp';
array_slice(
array_map(
function($item) { return "http://" . $item;},
explode("http://", $test)),
1);
答案 5 :(得分:0)
为了通过正则表达式回答这个问题,我想你想要这样的事情:
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
$keywords = preg_split("/.http:\/\//",$test);
print_r($keywords);
它会返回您需要的内容:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jp
[1] => localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)