В дальнейшей работе мне понадобится много обращаться к адресной строке браузера и на основе запроса пользователя перенаправлять его на нужную страницу.
Для этого я написал класс для работы с URL в нём я активно использую стандартную функцию PHP parse_url() и свой класс DataCleaner для очистки.
Здесь я тоже посторался учеть как можно больше вариантов использования которые мне могут понадобиться в дальнейшем.
Покажу весь код сразу:
<?php
class UrlParse
{
private $url = [];
private $query = [];
public function __construct()
{
$this->url = explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
$this->query = explode('&', parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY));
}
/**
* Возвращает массив частей URL расделённых /
* @return array
*/
public function getUrlPath() :array
{
return DataCleaner::cleanStringArray($this->url);
}
/**
* Возвращает количество элементов в массиве URL
* @return int
*/
public function getCountUrlPath() :int
{
return count($this->getUrlPath());
}
/**
* Возвращает значение массива URL по ключу
* Если значение ключа больше чем элеменов массива
* вернёт пустую строку
*
* @param int $num
* @return string
*/
public function getByNumUrlPath($num) :string
{
if(!is_int($num)) {
throw new Exception('Передан неверный тип параметра в метод ' . __METHOD__ .
' здесь ожидается число');
}
$url = DataCleaner::cleanStringArray($this->url);
$col = $this->getCountUrlPath();
if($num > $col) {
return '';
}
return $url[$num];
}
/**
* Возвращает следующий элемент URL после запрашиваемого
* если запрашиваемый элемент последний
* вернёт пустую строку
* @param string $query
* @return string
*/
public function getNextUrlPath($query) :string
{
$key = array_search($query, $this->url);
if (array_key_exists($key + 1, $this->url)) {
$item = $this->url[$key + 1];
$item = DataCleaner::cleanString($item);
return $item;
}
return '';
}
/**
* Возвращает массив с запросов в URL
*
* @return array
*/
public function getQueryUrl() :array
{
return DataCleaner::cleanStringArray($this->query);
}
/**
* Возвращает значение запроса в URL по ключу
* если ключ не существует
* вернёт пустую строку
*
* @param string $key
* @return int|string
*/
public function getQueryValueUrl($key)
{
foreach ($this->query as $item) {
$keyQuery = explode('=', $item);
if ($keyQuery[0] === $key) {
$value = $keyQuery[1];
return $value;
}
}
return '';
}
}
Теперь посмотрим что получилось, буду разбирать условный URL mysite.ru/cpanel/users/?user=23&post=12
Метод getUrlPath() — Возвращает массив частей URL расделённых /
array (size=4)
0 => string '' (length=0)
1 => string 'cpanel' (length=6)
2 => string 'users' (length=5)
3 => string '' (length=0)
Метод getCountUrlPath() — Возвращает количество элементов в массиве URL
Метод getByNumUrlPath() принимает в качестве параметра число и возвращает значение массива URL по ключу. Если значение ключа больше чем элеменов массива вернёт пустую строку
Метод getNextUrlPath() — Возвращает следующий элемент URL после запрашиваемого. Если запрашиваемый элемент последний вернёт пустую строку.
Метод getQueryUrl() — Возвращает массив с запросов в URL.
Метод getQueryValueUrl($key) — Возвращает значение запроса в URL по ключу. Если ключ не существует вернёт пустую строку.
Taxi moto line
128 Rue la Boétie
75008 Paris
+33 6 51 612 712
Taxi moto paris
Hello! I could have sworn I’ve been to this website before but after browsing through some of the
post I realized it’s new to me. Nonetheless, I’m definitely glad I found it and I’ll be book-marking and
checking back frequently!
This is a awfully good post. Thankyou towards keeping us informed. Fredra Bennie Lari
I was studying some of your articles on this site and I conceive this web site is really instructive! Keep putting up. Ruthanne Aldus Pirzada
I visited many web pages except the audio quality for audio songs existing at this website is genuinely wonderful. Maureene Darrick Jaycee
I love reading an article that will make men and women think. Also, thanks for allowing me to comment! Orelie Hillier Latimore
I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get got an edginess over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase. Katlin Eldredge Bourne
I think the problem for me is the energistically benchmark focused growth strategies via superior supply chains. Compellingly reintermediate mission-critical potentialities whereas cross functional scenarios. Phosfluorescently re-engineer distributed processes without standardized supply chains. Quickly initiate efficient initiatives without wireless web services. Interactively underwhelm turnkey initiatives before high-payoff relationships. Minnie Chuck Baskett
I have been surfing online more than 3 hours today, yet I never found any interesting article like yours. It?s pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the net will be much more useful than ever before. Eleen Abbey Michelle
I am looking forward to tasting some of the new food items. Annabal Nestor Kendell
very good put up, i certainly love this web site, carry on it Lisabeth Bondy Wilkinson
No matter if some one searches for his essential thing, thus he/she wishes to be available that in detail, thus that thing is maintained over here.| Ondrea Griffy Grand
Hey there! I just wish to give you a big thumbs up for the great information you have right here on this post. I will be coming back to your website for more soon. Larina Nels Abrams
I really appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again! Jayne Jean Marr
Usually I do not learn article on blogs, however I would like to say that this write-up very forced me to try and do it! Your writing taste has been surprised me. Thanks, very great post. Mariann Walker Denys
Wonderful article! We will be linking to this great article on our website. Keep up the good writing. Jinny Noah Mountford
below youll come across the link to some web pages that we consider you must visit Julissa Reinwald Rosenblatt
There is definately a lot to learn about this topic. I like all of the points you have made. Lura Bron Scoter Elena Alvie Kippy
Welcome to online casinos. Our online casinos are the best online casinos that offer you the most immediate casino bonus and no deposit bonus system for your players, giving you a real casino-like experience at home. Seana Elliott Cappello
The author of the book Waves Passing in the Night is Lawrence Weschler Georgeanna Jacques Trabue
Have you ever considered publishing an ebook or guest authoring on other blogs? I have a blog centered on the same subjects you discuss and would love to have you share some stories/information. I know my subscribers would appreciate your work. If you are even remotely interested, feel free to shoot me an e mail.| Merrie Jard Evanthe
Excellent article. I am experiencing some of these issues as well.. Angelica Ailbert Meeker