在php中使用正则表达式分割字符串

问题描述 投票:0回答:7

我是 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
)

我该怎么办?

php regex
7个回答
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);

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
)

1
投票

如果它们总是像这样 vith substr() 函数参考:http://php.net/manual/en/function.substr.php但是如果它们的长度是动态的,则可以拆分它们。您需要在第二个“http://”之前获得

;
或任何其他不太可能使用的符号,然后使用爆炸函数参考:http://php.net/manual/en/function。爆炸.php
$string = "http://something.com/;http://something2.com"; $a = explode(";",$string);


1
投票

尝试以下操作:

<?php
$temp = explode('http://', $test);
foreach($temp as $url) {
    $urls[] = 'http://' . $url;
}
print_r($urls);
?>

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);

0
投票

preg_split()
是分割这些 URL 的理想工具。使用前瞻来匹配 URL 的开头,而不会在拆分过程中消耗它。 演示

$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";

var_export(
    preg_split('#(?=http://)#', $test, 0, PREG_SPLIT_NO_EMPTY)
);

该模式将在第一个 URL 之前分割,不,从结果中过滤掉空元素很重要。防止在开始时分裂也可以通过在模式开始处使用

(?!^)
来实现。
preg_split('#(?!^)(?=http://)#', $test)

要匹配

http
https
,请使用
(?=https?://)


-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
)
© www.soinside.com 2019 - 2024. All rights reserved.