我是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
)
我该怎么办?
$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);
你要求一个正则表达式的解决方案,所以你在这里…
$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
)
如果它们总是这样,可以使用substr()函数参考:http://php.net/manual/en/function.substr.php拆分它们,但如果它们是动态长度。你需要得到一个;
或任何其他标志,不太可能在第二次"http://"之前使用,然后使用爆炸功能参考:http://php.net/manual/en/function.explode.php$string = "http://something.com/;http://something2.com"; $a = explode(";",$string);
尝试如下:
<?php
$temp = explode('http://', $test);
foreach($temp as $url) {
$urls[] = 'http://' . $url;
}
print_r($urls);
?>
$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);
对于用正则表达式回答这个问题,我认为您需要这样做:
$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
)