代码之家  ›  专栏  ›  技术社区  ›  itajackass

从字符串中提取链接,更改URL并在php中重建字符串

php
  •  0
  • itajackass  · 技术社区  · 5 年前

    有没有办法找到字符串中的所有URL,并将原始消息的每个主干保存在一个数组中?

    我的目标是截取url,用一个函数更改url中的一些参数,并重建原始字符串。

    例子:

    $original_string = "Hi, this is a list of urls: http://www.google.it, www.amazon.it, https://www.amzn.to/XXXXX and at the end we have www.example.it";
    

    预期结果:

    $result = array(
    0 => "Hi, this is a list of urls: ",
    1 => "http://www.google.it",
    2 => ", ",
    3 => "www.amazon.it",
    4 => ", ",
    5 => "https://www.amzn.to/XXXXX",
    6 => " and at the end we have ",
    7 => "www.example.it"
    );
    

    在这个结果之后,我可以用我已经完成的函数编辑我的链接,并重建字符串。

    我可以在一个字符串中找到所有URL,包括: preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $original_string, $urls);

    但我丢失了所有其他文字。。。

    更新:按照建议尝试了此代码,但我得到了奇怪的结果:

    $x = preg_split('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $original_string, -1, PREG_SPLIT_DELIM_CAPTURE);
    
    var_dump($x);
    
    
    
      array(9) {
      [0]=>
      string(28) "Hi, this is a list of urls: "
      [1]=>
      string(1) "t"
      [2]=>
      string(2) ", "
      [3]=>
      string(1) "t"
      [4]=>
      string(2) ", "
      [5]=>
      string(1) "X"
      [6]=>
      string(24) " and at the end we have "
      [7]=>
      string(1) "t"
      [8]=>
      string(0) ""
    }
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   astax    5 年前

    你最好的选择是 regular expressions .根据您最初的问题描述,您很可能需要使用 preg_replace_回调 函数,而不是将字符串拆分为数组,对其进行处理和重新组装。

    我不能说这是一个可靠的来源,但从 PHP: Regular Expression to get a URL from a string 如果需要创建正则表达式的帮助。或者只是使用网络搜索:)

    这个在线工具对于更好地理解regexp很有用- https://regex101.com/

    下面是一个例子,正则表达式取自 Extract URLs from text in PHP

    $pattern = '(?xi)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))';
    
    var_export(preg_replace_callback("#$pattern#i", function($matches) {
        $url = $matches[0];
        // put your code here. Or call your existing function/method with the $url parameter
        return '->' . $url . '<-';
      }, $original_string) ));