簡體   English   中英

用PHP削減字符串

[英]cutting string down in PHP

我正在處理一些非常簡單的問題,但是我發現解決起來很漫長。

我有一個字符串,該字符串的網址由用戶管理...因此可以是:

是否有一種簡單的方法可以識別並僅將其剪切到mydomain.com? 這樣,它將保持統一?

function after ($this, $inthat) {
if (!is_bool(strpos($inthat, $this)))
return substr($inthat, strpos($inthat,$this)+strlen($this));
};
$web_data="";
if(!strpos($data["web"], "http://") {
$web_data=after ("http:\\", $data["concert_web"]);
}
if(!strpos($data["web"], "https://") {
$web_data=after ("https://", $data["concert_web"]);
}
if(!strpos($data["web"], "www") {
$web_data=after ("www", $data["concert_web"]);
}

我收集了該腳本,但感覺不對,可以適應未來嗎? 我渴望學習,並在此先感謝您的任何評論。

我個人將regex與preg_replace結合使用。 像這樣:

// Strings for testing the case.
$domains = [
  'foodomain.com',
  'www.foodomain.com',
  'http://foodomain.com',
  'https://www.foodomain.com',
  'https://www.foodomain.www.com',
];


$result_strings = preg_replace(
  [
    '#^https?://#', // First, remove protocol.
    '#^www.#',      // Remove www. from the beginning.
  ],
  '', // Replace by an empty string.
  $domains // You can pass your string here.
);

print_r($result_strings);  // It will output result string for each of the domains from $domains array.

輸出:

Array
(
    [0] => foodomain.com
    [1] => foodomain.com
    [2] => foodomain.com
    [3] => foodomain.com
    [4] => foodomain.www.com
)

您可以將parse_url($URL, PHP_URL_HOST)AbraCadaver和RegEx(通過preg_match() )組合使用。

<?php

$URL = 'https://www.sub.domain.tld/file.php?okay=true';
preg_match('/([^\.]+\.[^\.]+)$/', parse_url($URL, PHP_URL_HOST), $m);
$DomainOnly = $m[1];

?>

$DomainOnly將是domain.tld 所有子域都將被修剪掉。

暫無
暫無

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

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