有没有人愿意帮我用regex过滤一个URL?我已经走得很远了,但我遇到了最后一个问题。
场景是这样的。
我怎么做才能使脚本也能去除 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;
}
使用 检索词 模式
^(?: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
我会使用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。