Substringer.php 6.84 KB
<?php

/**
 * ====================================================================================================================|
 * Компонент, который служит для обрезания строк по заданным параметрам
 * ====================================================================================================================|
 */

namespace common\components;

use yii\base\Object;

/**
 * Class Substringer
 * @package common\components
 * ====================================================================================================================|
 * @method @static simpleStringSubstring
 * @method @static changeStringByRegex
 * ====================================================================================================================|
 */
class Substringer extends Object
{


	/**
	 * @param string $haystack
	 * @param string $needle
	 * @param bool $reverse
	 * @return string
	 *=================================================================================================================|
	 * @static
	 * Метод, который берет строку, и обрезает её до заданного момента
	 *=================================================================================================================|
	 * @todo
	 * Пока что метод адекватно работает только при том условии, что нужный нам символ/комбинация символов является
	 * первой при поисковом запросе, нужно допилить логику, если например:
	 * $haystack='www.site.com?sort=title_act&sort=category-1&sort=test_val_desc
	 * то, обрезать всё до нужной комбинации
	 *=================================================================================================================|
	 * @example 1
	 * Start Data:
	 *  $haystack='https://www.youtube.com?v=OBwS66EBUcY
	 *  $needle='?';
	 * Return result:
	 * $res='https://www.youtube.com/watch';
	 * @example 2
	 * Start data
	 * $haystack='https://www.youtube.com/watch?v=OBwS66EBUcY';
	 * $needle ='?';
	 * $res = '?v=OBwS66EBUcY'
	 *
	 */
	public static function simpleStringSubstring(string $haystack, string $needle): string
	{
		$deletePosition = strpos($haystack, $needle);
		if ($deletePosition == 0)
			return $haystack;
		$result = substr($haystack, 0, $deletePosition);
		return $result;
	}







	/**
	 * @param string $haystack
	 * @param string $regex1
	 * @param string $regex2
	 * @param string $requiredDelimiter
	 * @param string $firstConcatenateSymbol
	 * @param string $secondConcatenateSymbol
	 * @return string
	 * ================================================================================================================|
	 * Метод, который берет $haystack, а так же 2 Regex паттерна
	 *    1) пытается найти regex совпадения
	 *          если их нет  @return original $haystack
	 *    2) вырезает всё лишнее со строки с помощью self::Substringer
	 *    3) конкатенирует между собой то,что получилось за принципом
	 *              mainString+delimiter1+regex1Result+delimiter2+regex2Result
	 * ================================================================================================================|
	 * @example
	 * $haystack='https://www.linija-svitla.ua/catalog/ulichnoe-osveshchenie?page_num=3&fcatlist=3268%2C&sort=test_test&3269%2C3270%2C3272%2C3273%2C3274%2C3275&page=50&per-page=18';
	 *  $regex1='/(\??|&?)page=\d{1,5}&per-page=\d{1,5}/';
	 *  $regex2='/(\?|&)sort=[a-zA-z_]+/';
	 *  $requiredDelimiter='?';
	 *  $firstConcatenateSymbol='?';
	 * $secondConcatenateSymbol='&';
	 * $res=$this->changeStringByRegex($haystack,$regex1,$regex2,$firstConcatenateSymbol,$secondConcatenateSymbol,$requiredDelimiter);
	 * @example-return
	 * https://www.linija-svitla.ua/catalog/ulichnoe-osveshchenie?page=50&per-page=18&sort=test_test
	 * ================================================================================================================|
	 * @todo
	 *  1) Пока что метод работает только с 2 regex,надо будет поменять строго regex string => regex array
	 *  2) Метод полюбому обрезает первый символ результирующей строки  regex
	 *  3) нужно сделать механизм замены строки только по 1 regex
	 * ================================================================================================================|
	 *
	 */
	/**
	 * @param string $haystack
	 * @param string $regex1
	 * @param string $regex2
	 * @param string $requiredDelimiter
	 * @param string $firstConcatenateSymbol
	 * @param string $secondConcatenateSymbol
	 *
	 * @return string
	 */
	public static function changeStringByRegex(string $haystack, string $regex1, string $regex2, string $requiredDelimiter = '',
	                                           string $firstConcatenateSymbol = '',
	                                           string $secondConcatenateSymbol = ''
	): string
	{

		# 1 give rexe1/regex2 parts
		# IF we have no consilience with both Regex == >  return $haystack
		if (preg_match($regex1, $haystack) !== 0 || preg_match($regex2, $haystack) !== 0) {
			preg_match($regex1, $haystack, $matches[0]);
			preg_match($regex2, $haystack, $matches[1]);
		} else return $haystack;

		# 2 give must part of string
		$mustPartOfstring = self::SimpleStringSubstring($haystack, $requiredDelimiter);

		# 3 if regex1/regex2 !empty concatenate they with $mustPartOfString
		if (isset($matches[0][0]) && isset($matches[1][0])) {
			# удаляем первый символ ( прим; $matches[0][0]='&sort=test_desc')
			# нам надо только текст без первого спецсимвола
			$matches[0][0] = substr($matches[0][0], 1);
			$mustPartOfstring = (isset($matches[0][0])) ? $mustPartOfstring . $firstConcatenateSymbol . $matches[0][0] : $mustPartOfstring;
			$matches[1][0] = substr($matches[1][0], 1);
			$mustPartOfstring = (isset($matches[1][0])) ? $mustPartOfstring . $secondConcatenateSymbol . $matches[1][0] : $mustPartOfstring;
		} # если найден только 1й regex
		elseif (isset($matches[0][0]) && !isset($matches[1][0])) {
			$matches[0][0] = substr($matches[0][0], 1);
			$mustPartOfstring = (isset($matches[0][0])) ? $mustPartOfstring . $firstConcatenateSymbol . $matches[0][0] : $mustPartOfstring;
		} # если найден 2й regex
		elseif (!isset($matches[0][0]) && isset($matches[1][0])) {
			$matches[1][0] = substr($matches[1][0], 1);
			$mustPartOfstring = (isset($matches[1][0])) ? $mustPartOfstring . $firstConcatenateSymbol . $matches[1][0] : $mustPartOfstring;
		}

		return $mustPartOfstring;


	}


}