使用preg_replace向链接添加尾部斜杠

时间:2017-07-28 18:19:29

标签: php regex preg-replace

我的网站内容中有一些内部链接没有尾随" /"它给我带来了一些爬行问题。想要搜索并替换这些链接。因此https://www.example.com/slug应该成为https://www.example.com/slug/。我正在使用以下功能来推送页面的整个内容并替换页面上的所有必要链接:

$string ='
<a href="https://www.example.com/slug1/page">1</a><br/>
<a href="https://www.example.com/slug2/page">2</a><br/>
<a href="https://www.example.com/slug1/page/">3</a><br/>
<a href="https://www.example.com/slug2/page/">4</a><br/>
<a href="https://www.example.com/">5</a><br/>
<a href="https://www.example.com">5b</a><br/>
<a href="https://www.example.com/style.css">6</a><br/>
<a href="https://www.example.com/style.jpg">7</a><br/>
<a href="https://www.example.com/style.png">8</a><br/>
<a href="https://www.example.com/style.pdf">9</a><br/>
';

echo str_replace_links($string, $switch);

我尝试用字符串测试几个链接:

<a href="https://www.example.com/page/>1</a><br/>
<a href="https://www.example.com/page/>2</a><br/>
<a href="https://www.example.com//>3</a><br/>
<a href="https://www.example.com//>4</a><br/>
<a href="https://www.example.com//>5</a><br/>
<a href="https://www.example.com/>5b</a><br/>
<a href="https://www.example.com/st/le.css">6</a><br/>
<a href="https://www.example.com/st/le.jpg">7</a><br/>
<a href="https://www.example.com/st/le.png">8</a><br/>
<a href="https://www.example.com/st/le.pdf">9</a><br/>

然而,这并没有产生正确的结果:

func toEnglishNumber(number: String) -> NSNumber {

       var result:NSNumber = 0

    let numberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: "EN")
    if let finalText = numberFormatter.number(from: number)
    {
        print("Intial text is: ", number)
        print("Final text is: ", finalText)


        result =  finalText

    }


     return result
}

任何有关正则表达式的帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用经过调整的URL验证程序来执行此操作。

(?i) (?<= " ) ( # (1 start) (?! mailto: ) (?: [a-z]* :\/\/ )? (?: \S+ (?: : \S* )? @ )? (?: (?: (?: [1-9] \d? | 1 \d\d | 2 [01] \d | 22 [0-3] ) (?: \. (?: 1? \d{1,2} | 2 [0-4] \d | 25 [0-5] ) ){2} (?: \. (?: [1-9] \d? | 1 \d\d | 2 [0-4] \d | 25 [0-4] ) ) | (?: (?: [a-z\x{a1}-\x{ffff}0-9]+ -? )* [a-z\x{a1}-\x{ffff}0-9]+ ) (?: \. (?: [a-z\x{a1}-\x{ffff}0-9]+ -? )* [a-z\x{a1}-\x{ffff}0-9]+ )* (?: \. (?: [a-z\x{a1}-\x{ffff}]{2,} ) ) ) | localhost ) ( : \d{2,5} )? # (2) (?: \/ (?: [^\s/]* / )* [^\s/.]+ )? ) # (1 end) (?= " )

https://regex101.com/r/GcT8ZU/1

格式化

public function indexAction(Request $request)
{
    $request->attributes->set('_controller', 'AppBundle\Controller\ExampleController::exampleAction');
    try{
        $this->get('debug.controller_resolver')->getController($request);
    } catch (\Exception $e) {
        $x = $e->getCode();
    }
}