簡體   English   中英

在php中使用正則表達式拆分字符串

[英]Split string using regular expression in php

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

你可以拆分它們,如果它們總是像這個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); $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
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM