在PHP中使用regex过滤URL

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

有没有人愿意帮我用regex过滤一个URL?我已经走得很远了,但我遇到了最后一个问题。

场景是这样的。

  1. 用户在Gravity Forms网站上提交SoundCloud歌曲的链接。
  2. 如果用户不添加,脚本会自动广告https:/自动。
  3. 移除 www.m. 从URL中获取。
  4. 有时会提交一个带有私人URL扩展名的链接。https:/soundcloud.comusernamesongtitles-qciX1vDI2Cq。

我怎么做才能使脚本也能去除 s-qciX1vDI2Cq 也是来自URL的?

输入示例http:/www.soundcloud.comusernamesongtitles-qciX1vDI2Cq

输出示例https:/soundcloud.comusernamesongtitle。

非常感谢!

add_filter( 'gform_pre_render', 'itsg_check_website_field_value' );
add_filter( 'gform_pre_validation', 'itsg_check_website_field_value' );
function itsg_check_website_field_value( $form ) {
    foreach ( $form['fields'] as &$field ) {  // for all form fields
        if ( 'website' == $field['type'] || ( isset( $field['inputType'] ) && 'website' == $field['inputType']) ) {  // select the fields that are 'website' type
            $value = RGFormsModel::get_field_value($field);  // get the value of the field

            if (! empty($value) ) { // if value not empty
                $field_id = $field['id'];  // get the field id

                if (! preg_match("~^(?:f|ht)tps?://~i", $value) ) {  // if value does not start with ftp:// http:// or https://
                    $value = "https://" . $value;  // add https:// to start of value
                }

                if ( preg_match("/(https?:\/\/)(www\.|m\.)?soundcloud\.com\/([^\s\n]+)\/([^\s\n]+)\/([^\s\n]+)", $value)) {
                    $temp = explode("/", $value);
                    array_pop($temp);
                    $value = implode("/", $temp);
                }


                preg_match("/(https?:\/\/)(www\.|m\.)?([^\s\n]+)(\/+)?/", $value, $extractedDomain);
                $value = "https://" . $extractedDomain[3];

                preg_match('/^(.*?)(\?.*)?$/', $value, $noSearch);
                $value = trim($noSearch[1], '/') . '';

                $_POST['input_' . $field_id] = $value; // update post with new value
            }
        }
    }
    return $form;
}
php regex filter preg-match
1个回答
0
投票

使用 检索词 模式

^(?:https?:\/\/|)(?:www|m)\.(soundcloud\.com\/[^\/]+\/[^\/]+)(?:\/.*?|)$

并替换成

http://$1

测试并查看解释(右上角)在 https:/regex101.comrmwa4JP1


请看 PHP 演示于 https:/www.ideone.comrdKb3P

preg_replace("/^(?:https?:\/\/|)(?:www|m)\.(soundcloud\.com\/[^\/]+\/[^\/]+)(?:\/.*?|)$/",
             "http://$1", $input);

要接受大写字母在可选的 www.m. 中的前缀和or。soundcloud.com 域名,添加 i regex修饰符。

/^(?:https?:\/\/|)(?:www|m)\.(soundcloud\.com\/[^\/]+\/[^\/]+)(?:\/.*?|)$/i

-1
投票

我会使用regex'/'。

$url = 'http://www.soundcloud.com/username/songtitle/s-qciX1vDI2Cq';
$regex = '/\//';
$a = preg_split($regex, $url);
print_r($a);

输出。

Array
(
    [0] => http:
    [1] =>
    [2] => www.soundcloud.com
    [3] => username
    [4] => songtitle
    [5] => s-qciX1vDI2Cq
)

现在你可以把这些元素从0到4连接起来 以获得正确的URL。

© www.soinside.com 2019 - 2024. All rights reserved.