Best Cucumber Common Library code snippet using StringUtils.replace
StringUtils.php
Source:StringUtils.php  
...266            : strtoupper($str);267    }268    /**269     * Replaces a `string` with another `string` inside a larger `string`, for270     * the first maximum number of values to replace of the search `string`.271     *272     *     StringUtils::replace(null, *, *, *)         // null273     *     StringUtils::replace('', *, *, *)           // ''274     *     StringUtils::replace('any', null, *, *)     // 'any'275     *     StringUtils::replace('any', *, null, *)     // 'any'276     *     StringUtils::replace('any', '', *, *)       // 'any'277     *     StringUtils::replace('any', *, *, 0)        // 'any'278     *     StringUtils::replace('abaa', 'a', null, -1) // 'abaa'279     *     StringUtils::replace('abaa', 'a', '', -1)   // 'b'280     *     StringUtils::replace('abaa', 'a', 'z', 0)   // 'abaa'281     *     StringUtils::replace('abaa', 'a', 'z', 1)   // 'zbaa'282     *     StringUtils::replace('abaa', 'a', 'z', 2)   // 'zbza'283     *     StringUtils::replace('abaa', 'a', 'z', -1)  // 'zbzz'284     *285     * @param string $text The `string` to search and replace in.286     * @param string $search The `string` to search for.287     * @param string $replace The `string` to replace $search with.288     * @param integer $max The maximum number of values to replace, or `-1`289     *                         if no maximum.290     *291     * @return string The text with any replacements processed or `null` if292     *    `null` `string` input.293     */294    public static function replaceReg($text, $search, $replace, $max = -1)295    {296        if ((true === self::isEmpty($text))297            || (true === self::isEmpty($search))298            || (null === $replace)299            || (0 === $max)300        ) {301            return $text;302        }303        return \preg_replace(304            '/' . \preg_quote($search) . '/',305            $replace,306            $text,307            $max308        );309    }310    /**311     * Replaces a `string` with another `string` inside a larger `string`, for312     * the first maximum number of values to replace of the search `string`.313     *314     *     StringUtils::replace(null, *, *, *)         // null315     *     StringUtils::replace('', *, *, *)           // ''316     *     StringUtils::replace('any', null, *, *)     // 'any'317     *     StringUtils::replace('any', *, null, *)     // 'any'318     *     StringUtils::replace('any', '', *, *)       // 'any'319     *     StringUtils::replace('any', *, *, 0)        // 'any'320     *     StringUtils::replace('abaa', 'a', null, -1) // 'abaa'321     *     StringUtils::replace('abaa', 'a', '', -1)   // 'b'322     *     StringUtils::replace('abaa', 'a', 'z', 0)   // 'abaa'323     *     StringUtils::replace('abaa', 'a', 'z', 1)   // 'zbaa'324     *     StringUtils::replace('abaa', 'a', 'z', 2)   // 'zbza'325     *     StringUtils::replace('abaa', 'a', 'z', -1)  // 'zbzz'326     *327     * @param string $text The `string` to search and replace in.328     * @param string $search The `string` to search for.329     * @param string $replace The `string` to replace $search with.330     * @param integer $max The maximum number of values to replace, or `-1`331     *                         if no maximum.332     *333     * @return string The text with any replacements processed or `null` if334     *    `null` `string` input.335     */336    public static function replace($text, $search, $replace, $max = null)337    {338        if ((true === self::isEmpty($text))339            || (true === self::isEmpty($search))340            || (null === $replace)341            || (0 === $max)342        ) {343            return $text;344        }345        return str_replace(346            $search,347            $replace,348            $text,349            $max350        );351    }352    /* -------------------------------------------------------------------------353     * Trim354     * ---------------------------------------------------------------------- */355    /**356     * Removes control characters (char <= 32) from both ends of a `string`,357     * handling `null` by returning `null`.358     *359     * This method removes start and end characters <= 32. To strip360     * whitespace use {@see strip}.361     *...StringUtils.class.php
Source:StringUtils.class.php  
...60	// @desc 		Transforma caracteres brancos ocupando 2 ou mais posições61	// 				em um caractere de espaço simples (ord 32)62	// @access		public	63	// @param 		str string		String a ser formatada64	// @param		replace string	" " String de substituição65	// @return 		string Novo valor da string66	// @see 		StringUtils::allTrim67	// @static	68	//!-----------------------------------------------------------------69	function stripBlank($str, $replace=' ') {70		return ereg_replace("[[:blank:]]{1,}", $replace, $str);71	}72	73	//!-----------------------------------------------------------------74	// @function 	StringUtils::left75	// @desc 		Retorna a quantidade indicada de caracteres de76	// 				uma string fornecida a partir da esquerda77	// @access		public	78	// @param 		str string		String a ser utilizada79	// @param 		chars int		"0" Número de caracteres solicitados80	// @return 		string Quantidade solicitada ou toda a string se o parâmetro81	// 				chars fornecido for igual a ""82	// @see 		StringUtils::right83	// @see 		StringUtils::mid84	// @static	85	//!-----------------------------------------------------------------86	function left($str, $chars = 0) {87		if (!TypeUtils::isInteger($chars)) {88			return $str;89		} else if ($chars == 0) {90			return '';91		} else {92			return substr($str, 0, $chars);93		}94	}95	96	//!-----------------------------------------------------------------97	// @function 	StringUtils::right98	// @desc 		Retorna a quantidade indicada de caracteres de99	// 				uma string fornecida a partir da direita100	// @access		public	101	// @param 		str string		String a ser utilizada102	// @param 		chars int		"0" Número de caracteres solicitados103	// @return 		string Quantidade solicitada ou toda a string se o parâmetro104	// 				chars fornecido for igual a ""105	// @see 		StringUtils::left106	// @see 		StringUtils::mid107	// @static	108	//!-----------------------------------------------------------------109	function right($str, $chars = 0) {110		if (!TypeUtils::isInteger($chars)) {111			return $str;112		} else if ($chars == 0) {113			return '';114		} else {115			return substr($str, strlen($str) - $chars, strlen($str)-1);116		}117	}118	119	//!-----------------------------------------------------------------120	// @function 	StringUtils::mid121	// @desc 		Retorna uma porção interna de uma string indicada122	// 				pelo delimitador de início `startAt` e pelo número123	// 				de caracteres `chars`124	// @access		public	125	// @param 		str string		String original126	// @param 		startAt int		"1" Posição inicial127	// @param 		chars int		"0" Quantidade de caracteres solicitados128	// @return 		string Novo valor da string129	// @see 		StringUtils::left130	// @see 		StringUtils::right131	// @static	132	//!-----------------------------------------------------------------133	function mid($str, $startAt = 1, $chars = 0) {134		if (!TypeUtils::isInteger($chars)) {135			return $str;136		} else if ($str == '' || $chars == 0) {137			return '';138		} else if (($startAt + $chars) > strlen($str)) {139			return $str;140		} else {141			if ($startAt == 0) $startAt = 1;142			return substr($str, $startAt-1, $chars);143		}144	}145	146	//!-----------------------------------------------------------------147	// @function	StringUtils::charAt148	// @desc		Retorna o caractere na posição $index do string $str149	// @access		public150	// @param		str string	String a ser consultado151	// @param		index int	Índice do caractere buscado152	// @return		string Valor do caractere ou vazio para índices inválidos153	// @static	154	//!-----------------------------------------------------------------155	function charAt($str, $index) {156		if (!TypeUtils::isInteger($index)) {157			return '';158		} else if ($str == '' || $index < 0 || $index >= strlen($str)) {159			return '';160		} else {161			$strTranslated = TypeUtils::parseString($str);162			return $strTranslated{$index};163		}164	}165	166	//!-----------------------------------------------------------------167	// @function 	StringUtils::match168	// @desc 		Busca por um valor dentro de um texto, levando169	// 				em consideração o caso (maiúsculas/minúsculas)170	// @access		public	171	// @param		str string			String base para a busca172	// @param 		sValue string		Valor a ser buscado173	// @param 		caseSensitive bool	"TRUE" Indica se a busca considera ou não letras maiúsculas/minúsculas174	// @return		bool175	// @static	176	//!-----------------------------------------------------------------177	function match($str, $sValue, $caseSensitive = TRUE) {178		if (!$caseSensitive) $sValue = strtolower($sValue);179		if (strlen($sValue) == 0) {180			return FALSE;181		} else {182			$pos = strpos($str, $sValue);183			return (!TypeUtils::isFalse($pos));184		}185	}186	187	//!-----------------------------------------------------------------188	// @function 	StringUtils::startsWith189	// @desc 		Verifica se o início de uma string corresponde190	// 				ao valor do parâmetro 'slice'191	// @access		public	192	// @param 		str string			String a ser testada193	// @param 		slice string		Porção de string194	// @param 		caseSensitive bool	"TRUE" Indica se a busca considera ou não letras maiúsculas/minúsculas195	// @param 		ignSpaces bool		"TRUE" Retirar espaços em branco à esquerda para realizar a busca196	// @return		bool197	// @see 		StringUtils::endsWith198	// @static	199	//!-----------------------------------------------------------------200	function startsWith($str, $slice, $caseSensitive = TRUE, $ignSpaces = TRUE) {201		if (!$caseSensitive) {202			$strUsed = ($ignSpaces) ? ltrim(strtolower($str)) : strtolower($str);203			$sliceUsed = strtolower($slice);204		} else {205			$strUsed = ($ignSpaces) ? ltrim($str) : $str;206			$sliceUsed = $slice;207		}208		return (StringUtils::left($strUsed, strlen($sliceUsed)) == $sliceUsed);209	}210	211	//!-----------------------------------------------------------------212	// @function 	StringUtils::endsWith213	// @desc 		Verifica se o final de uma string corresponde214	// 				ao valor do parâmetro 'slice'215	// @access		public	216	// @param 		str string			String a ser testada217	// @param 		slice string			Porção de string218	// @param 		caseSensitive bool	"TRUE" Indica se a busca considera ou não letras maiúsculas/minúsculas219	// @param 		ignSpaces bool		"TRUE" Retirar espaços em branco à direita para realizar a busca220	// @return		bool221	// @see 		StringUtils::startsWith222	// @static	223	//!-----------------------------------------------------------------224	function endsWith($str, $slice, $caseSensitive = TRUE, $ignSpaces = TRUE) {225		if (!$caseSensitive) {226			$strUsed = ($ignSpaces) ? rtrim(strtolower($str)) : strtolower($str);227			$sliceUsed = strtolower($slice);228		} else {229			$strUsed = ($ignSpaces) ? rtrim($str) : $str;230			$sliceUsed = $slice;231		}232		return (StringUtils::right($strUsed, strlen($sliceUsed)) == $sliceUsed);233	}234	235	//!-----------------------------------------------------------------236	// @function 	StringUtils::isAllUpper237	// @desc 		Verifica se uma string é composta apenas por238	// 				letras maiúsculas239	// @access		public	240	// @param 		str string		String a ser verificada241	// @return		bool242	// @see 		StringUtils::isAllLower243	// @static	244	//!-----------------------------------------------------------------245	function isAllUpper($str) {246		return (TypeUtils::isFalse(ereg('[a-z]', $str)));247	}248	249	//!-----------------------------------------------------------------250	// @function 	StringUtils::isAllLower251	// @desc 		Verifica se uma string é composta apenas por252	// 				letras minúsculas253	// @access		public	254	// @param 		str string		String a ser verificada255	// @return		bool256	// @see			StringUtils::isAllUpper257	// @static	258	//!-----------------------------------------------------------------259	function isAllLower($string) {260		return (TypeUtils::isFalse(ereg('[A-Z]', $string)));261	}262	263	//!-----------------------------------------------------------------264	// @function	StringUtils::ifEmpty265	// @desc		Substitui a string por um valor de substituição caso ela seja vazia266	// @access		public267	// @param		value string		Valor original268	// @param		replacement string	Valor de substituição269	// @return		string270	// @static271	//!-----------------------------------------------------------------272	function ifEmpty($value, $replacement) {273		return (empty($value) ? $replacement : $value);274	}275	276	//!-----------------------------------------------------------------277	// @function	StringUtils::concat278	// @desc		Concatena um valor no final da string279	// @access		public280	// @param		str string		String original281	// @param		concat string	Valor a ser concatenado282	// @return		string Novo valor da string283	// @static	284	//!-----------------------------------------------------------------285	function concat($str, $concat) {286		return $str . $concat;287	}288	289	//!-----------------------------------------------------------------290	// @function	StringUtils::surround291	// @desc		Insere prefixo e sufixo em uma determinada string292	// @access		public293	// @param		str string		String original294	// @param		prefix string	Prefixo295	// @param		suffix string	Sufixo296	// @static	297	//!-----------------------------------------------------------------298	function surround($str, $prefix, $suffix) {299		return $prefix . $str . $suffix;300	}301	302	//!-----------------------------------------------------------------303	// @function 	StringUtils::insert304	// @desc 		Insere um valor na posição indicada de uma string305	// @access		public	306	// @param 		str string		String original307	// @param 		insValue string	"" Valor a ser inserido308	// @param 		insPos int		"0" Posição para inserir a string309	// @return 		string Novo valor da string310	// @static	311	//!-----------------------------------------------------------------312	function insert($str, $insValue = '', $insPos = 0) {313		if (($insValue == '') || ($insPos < 0) || ($insPos > strlen($str))) {314			return $str;315		} else if ($insPos == 0) {316			return $insValue . $str;317		} else if ($insPos == strlen($str)) {318			return $str . $insValue;319		} else {320			return StringUtils::left($str, $insPos) . $insValue . StringUtils::right($str, $insPos, strlen($str) - $insPos);321		}322	}323	324	//!-----------------------------------------------------------------325	// @function	StringUtils::implode326	// @desc		Cria uma string a partir da união dos elementos de um array327	// @access		public328	// @param		values array	Array de valores329	// @param		glue string		String utilizada para unir os valores330	// @return		string331	// @static332	//!-----------------------------------------------------------------333	function implode($values, $glue) {334		return implode($glue, (array)$values);335	}336	337	//!-----------------------------------------------------------------338	// @function	StringUtils::encode339	// @desc		Codifica uma string de acordo com um padrão340	// @access		public341	// @param		str string			String a ser codificada342	// @param		encodeType string	Tipo de codificação343	// @param		params array		"NULL" Vetor de parâmetros ou argumentos para a codificação344	// @return		string String codificada345	// @note		Parâmetros disponíveis por tipo de codificação:346	//				- 7bit: {nl}347	//				- 8bit: {nl}348	//				- quoted-printable: {charset}349	// @static	350	//!-----------------------------------------------------------------351	function encode($str, $encodeType, $params=NULL) {		352		switch(strtolower($encodeType)) {353			case 'base64' :354				$encoded = chunk_split(base64_encode($str));355				break;356			case 'utf8' :357				$encoded = utf8_encode($str);358				break;359			case '7bit' :360			case '8bit' :361				$nl = TypeUtils::ifNull($params['nl'], "\n");362				$str = str_replace(array("\r\n", "\r"), array("\n", "\n"), $str);363				$encoded = str_replace("\n", $nl, $str);364				if (!StringUtils::endsWith($encoded, $nl))365					$encoded .= $nl;366				break;367			case 'quoted-printable' :368				static $qpChars;369				if (!isset($qpChars))370					$qpChars = array_merge(array(64, 61, 46), range(0, 31), range(127, 255));371				$charset = TypeUtils::ifNull($params['charset'], PHP2Go::getConfigVal('CHARSET', FALSE));372				$replace = array(' ' => '_');373				foreach ($qpChars as $char)374					$replace[chr($char)] = '=' . strtoupper(dechex($char));375				return sprintf("=?%s?Q?%s=", $charset, strtr($str, $replace));376			default:377				$encoded = $str;378				break;379		}380		return $encoded;	381	}382	383	//!-----------------------------------------------------------------384	// @function	StringUtils::decode385	// @desc		Decodifica uma string, utilizando um padrão386	// @access		public387	// @param		str string			String a ser decodificada388	// @param		encodeType string	Tipo de codificação atual da string389	// @return		string Valor decodificado390	// @static391	//!-----------------------------------------------------------------392	function decode($str, $encodeType) {393		switch(strtolower($encodeType)) {394			case 'base64' :395				$decoded = base64_decode($str);396				break;397			case 'utf8' :398				$decoded = utf8_decode($str);399				break;400			case 'quoted-printable' :401				$decoded = quoted_printable_decode($str);402				break;403			default :404				$decoded = $str;405				break;406		}407		return $decoded;408	}409	410	//!-----------------------------------------------------------------411	// @function 	StringUtils::filter412	// @desc 		Filtra uma string retirando o tipo de caractere413	// 				indicado no parâmetro 'filterType'414	// @access		public	415	// @param 		str string			String a ser filtrada416	// @param 		filterType string		"alphanum" Tipo de caractere a ser filtrado417	// @return 		string String sem todas as ocorrências do tipo de caractere solicitado418	// @note 		O tipo de filtro aceita os valores alpha (alfanuméricos),419	// 				alphalower (alfanuméricos minúsculos), alphaupper (alfanuméricos maiúsculos),420	// 				num (números), alphanum (alfanuméricos e números) e htmlentities (elementos html)421	// @see 		StringUtils::escape422	// @see 		StringUtils::normalize423	// @static	424	//!-----------------------------------------------------------------425	function filter($str, $filterType = 'alphanum', $replaceStr='') {426		$replaceStr = TypeUtils::parseString($replaceStr);427		switch ($filterType) {428			case 'alpha' : 429				return (ereg_replace("[^a-zA-Z]", $replaceStr, $str));430			case 'alphalower' : 431				return (ereg_replace("[^a-z]", $replaceStr, $str));432			case 'alphaupper' : 433				return (ereg_replace("[^A-Z]", $replaceStr, $str));434			case 'num' : 435				return (ereg_replace("[^0-9]", $replaceStr, $str));436			case 'alphanum' : 437				return (ereg_replace("[^0-9a-zA-Z]", $replaceStr, $str));438			case 'htmlentities' : 439				return (ereg_replace("&[[:alnum:]]{0,};", $replaceStr, $str));440			case 'blank' : 441				return (ereg_replace("[[:blank:]]{1,}", $replaceStr, $str));442			default : 443				return $str;444		}445	}446	447	//!-----------------------------------------------------------------448	// @function 	StringUtils::escape449	// @desc 		Aplica conversões em um texto de acordo com um450	// 				dos padrões de conversão definidos451	// @access		public	452	// @param 		str string				Texto a ser processado453	// @param 		conversionType string		"html" Tipo de conversão para o texto454	// @note 		O tipo de conversão aceita os valores: 455	// 				html (conversão de caracteres especiais HTML),456	// 				htmlall (conversão de todos os caracteres para HTML),457	// 				url (codificação de url) ou458	// 				quotes (adiciona barras às haspas simples que não possuem barra)459	// @return 		strign Texto convertido segundo o padrão solicitado460	// @see 		StringUtils::filter461	// @see 		StringUtils::normalize462	// @static	463	//!-----------------------------------------------------------------464	function escape($str, $conversionType = 'html') {465		switch ($conversionType) {466			case 'html':  467				return htmlspecialchars($str, ENT_QUOTES);468			case 'htmlall' :469				return htmlentities($str, ENT_QUOTES);470			case 'url' : 471				return urlencode($str);472			case 'quotes' : 473				return preg_replace("%(?<!\\\\)'%", "\\'", $str);474			default : 475				return $str;476		}477	}478	479	//!-----------------------------------------------------------------480	// @function	StringUtils::capitalize481	// @desc		Capitaliza todas as palavras contidas em uma string482	// @access		public483	// @param		str string		String base484	// @return		string String com todas as palavras capitalizadas485	// @static486	//!-----------------------------------------------------------------487	function capitalize($str) {488		if (!empty($str)) {489			$w = preg_split("/\s+/", $str);490			for ($i=0, $s=sizeof($w); $i<$s; $i++) {491				if (empty($w[$i]))492					continue;493				$f = strtoupper($w[$i]{0});494				$r = strtolower(substr($w[$i], 1));495				$w[$i] = $f . $r;496			}497			return implode(' ', $w);498		}499		return $str;500	}501	502	//!-----------------------------------------------------------------503	// @function 	StringUtils::normalize504	// @desc 		Normaliza uma string substituindo caracteres ASCII505	// 				localizados nas posições 192-223 e 224-225 para seus506	// 				correspondentes caracteres 'normais' ->  áéíÁÈÒÖ para aeiAEOO507	// @access		public	508	// @param 		str string		String base para a substituição509	// @return 		string Valor da string normalizado510	// @see 		StringUtils::filter511	// @see 		StringUtils::escape512	// @static	513	//!-----------------------------------------------------------------514	function normalize($str) {515		$ts = array("/[À-Å]/", "/Æ/", "/Ç/", "/[È-Ë]/", "/[Ì-Ï]/", "/Ð/", "/Ñ/", "/[Ò-ÖØ]/", "/×/", "/[Ù-Ü]/", "/Ý/", "/ß/", "/[à-å]/", "/æ/", "/ç/", "/[è-ë]/", "/[ì-ï]/", "/ð/", "/ñ/", "/[ò-öø]/", "/÷/", "/[ù-ü]/", "/[ý-ÿ]/");516		$tn = array("A", "AE", "C", "E", "I", "D", "N", "O", "X", "U", "Y", "ss", "a", "ae", "c", "e", "i", "d", "n", "o", "x", "u", "y");517		return preg_replace($ts, $tn, $str);518	}519	520	//!-----------------------------------------------------------------521	// @function	StringUtils::cutBefore522	// @desc		Retira de uma string os caracteres antes de um determinado token523	// @access		public524	// @param		string string	String original525	// @param		token string	Token para pesquisa526	// @return		string Valor processado527	// @static528	//!-----------------------------------------------------------------529	function cutBefore($string, $token, $caseSensitive=TRUE) {530		if (StringUtils::match($caseSensitive ? $string : strtolower($string), $token, $caseSensitive)) {531			return stristr($string, $token);532		}533		return $string;534	}535	536	//!-----------------------------------------------------------------537	// @function	StringUtils::cutLastOcurrence538	// @desc		Remove a porção de string a partir da última ocorrência539	//				do parâmetro $cutOff em $string540	// @access		public541	// @param		string string		String original542	// @param		cutOff string		Token para busca e remoção543	// @param		caseSensitive bool	"TRUE" Sensível ou não ao caso544	// @return		string Valor processado545	// @static546	//!-----------------------------------------------------------------547	function cutLastOcurrence($string, $cutOff, $caseSensitive=TRUE) {548		if (!StringUtils::match($caseSensitive ? $string : strtolower($string), $cutOff, $caseSensitive))549			return $string;550		else551			return strrev(substr(stristr(strrev($string), strrev($cutOff)),strlen($cutOff)));552	}553	554	//!-----------------------------------------------------------------555	// @function 	StringUtils::indent556	// @desc 		Cria indentação em um texto utilizando o caractere557	// 				$iChar repetido $nChars vezes558	// @access		public	559	// @param 		str string		Texto a ser indentado560	// @param		nChars int		Tamanho da indentação561	// @param		iChar string		" " Caractere(s) para a indentação562	// @return		string String indentada563	// @static	564	//!-----------------------------------------------------------------565	function indent($str, $nChars, $iChar = ' ') {566		if (!TypeUtils::isInteger($nChars) || $nChars < 1) {567			$nChars = 1;568		}569		return preg_replace('!^!m', str_repeat($iChar, $nChars), $str);570	}571	572	//!-----------------------------------------------------------------573	// @function	StringUtils::truncate574	// @desc		Trunca um texto para o tamanho indicado por $length,575	// 				sufixando o resultado com o valor indicado em $truncSufix576	// @access		public	577	// @param 		str string			Texto a ser truncado578	// @param 		length int			Tamanho desejado do resultado579	// @param 		truncSufix string	"..." Sufixo para o resultado580	// @param 		forceBreak bool		"TRUE" Forçar quebra em palavras longas581	// @return		string String truncada ou a original se não exceder o tamanho582	// @static583	//!-----------------------------------------------------------------584	function truncate($str, $length, $truncSufix = '...', $forceBreak = TRUE) {585		if (!TypeUtils::isInteger($length) || $length < 1) {586			return '';587		} else {588			if (strlen($str) > $length) {589				$length -= strlen($truncSufix);590        		if (!$forceBreak)591            		$str = preg_replace('/\s+?(\S+)?$/', '', substr($str, 0, $length+1));		592				return substr($str, 0, $length) . $truncSufix;593			} else {594				return $str;595			}596		}597	}598	599	//!-----------------------------------------------------------------600	// @function 	StringUtils::insertChar601	// @desc 		Insere o caractere $char entre cada dupla de caracteres602	// 				encontrados no texto $str603	// @access		public	604	// @param 		str string		Texto original605	// @param 		char string		" " Caracter ou caracteres para inserção606	// @param 		stripEmpty bool	"TRUE" Ignorar caracteres vazios607	// @return		string String processada608	// @static	609	//!-----------------------------------------------------------------610	function insertChar($str, $char = ' ', $stripEmpty = TRUE) {611		if ($stripEmpty) {612			$strChars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);613		} else {614			$strChars = preg_split('//', $str, -1);615		}616		return implode($char, $strChars);617	}618	619	//!-----------------------------------------------------------------620	// @function	StringUtils::wrapLine621	// @desc		Reformata uma string ajustando-a para ter um número fixo622	//				de colunas, utilizando a quebra de linha 'breakString'623	//				fornecida624	// @access		public625	// @param		str string			Texto original626	// @param		num int				Posição de quebra de linha627	// @param		breakString string	"\n" String ou caractere para quebra de linha628	// @return		string Texto formatado629	// @see 		StringUtils::wrap630	// @see 		StringUtils::addLineNumbers	631	// @note		Ao contrário do método wrap, este método se632	//				aplica a uma só linha (é suposto que não existem quebras633	//				na variável $str fornecida)634	// @static635	//!-----------------------------------------------------------------636	function wrapLine($str, $num, $breakString="\n") {637		$line = '';638		$processed = '';639		$token = strtok($str, ' ');640		while($token) {641			if (strlen($line) + strlen($token) < ($num + 2)) {642				$line .= " $token";643			} else {644				$processed .= "$line$breakString";645				$line = $token;646			}647			$token = strtok(' ');648		}649		$processed .= $line;650		$processed = trim($processed);651		return $processed;652	}653	//!-----------------------------------------------------------------654	// @function 	StringUtils::wrap655	// @desc 		Quebra em múltiplas linhas um texto com 'num'656	// 				caracteres por linha (ou quebras de linha já657	// 				existentes) utilizando a quebra de linha 'breakString'658	// 				fornecida659	// @access		public	660	// @param 		str string			Texto original661	// @param 		num int				Posição de quebra de linha662	// @param 		breakString string	"\n" String ou caractere para quebra de linha663	// @return 		string Texto formatado com as novas quebras de linha664	// @see 		StringUtils::wrapLine665	// @see 		StringUtils::addLineNumbers666	// @static	667	//!-----------------------------------------------------------------668	function wrap($str, $num, $breakString="\n") {669		$str = ereg_replace("([^\r\n])\r\n([^\r\n])", "\\1 \\2", $str);670		$str = ereg_replace("[\r\n]*\r\n[\r\n]*", "\r\n\r\n", $str);671		$str = ereg_replace("[ ]* [ ]*", ' ', $str);672		$str = stripslashes($str);  673		$processed = '';	674		$paragraphs = explode("\n", $str);675		for ($i=0; $i<sizeOf($paragraphs); $i++) {676			$processed .= StringUtils::wrapLine($paragraphs[$i], $num, $breakString) . $breakString;677		}678		$processed = trim($processed);679		return $processed;680	}681	682	//!-----------------------------------------------------------------683	// @function 	StringUtils::addLineNumbers684	// @desc 		Adiciona numeração às linhas de um texto685	// @access		public	...AuthHelper.php
Source:AuthHelper.php  
...31            while (!feof($h))32            {33                $line = fgets($h);34                if (!$ns && strpos($line, 'namespace') !== false) {35                    $ns = trim(preg_replace('~\s*namespace\s+([\S]+).*~', '$1', $line));36                }37                if (!$class && strpos($line, 'class') !== false) {38                    $class = trim(preg_replace('/\s*class\s+(\w+).+/', '$1', $line));39                }40                if (!empty($ns) && !empty($class)) {41                    break;42                }43            }44            fclose($h);45            if (!empty($ns) && !empty($class)) {46                $ns = StringUtils::removeTail($ns, ";"); // bo dau ; cuoi cung )neu co47                $className = $ns . '\\' . $class;48                $controller = StringUtils::removeTail($class, "Controller");49                $controllerId = StringUtils::camel2Dash($controller);50                Yii::info("Controller found: " . $className . " (in $file)");51                $class = new ReflectionClass($className);52//                $methods = $class->getMethods();53                $objInstance = $class->newInstanceArgs(['id' => 'dummy', 'module' => 'dummy']);54//                echo $objInstance->id;55                $methods = (get_class_methods ($className));56                foreach ($methods as $method) {57                    $action = StringUtils::removeHead($method, "action");58                    $actionId = StringUtils::camel2Dash($action);59                    if (StringUtils::startsWith($method, "action") && !StringUtils::equal($method, "actions")) {60                        $route = new ActionPermission();61                        $route->appAlias = $alias;62                        $route->name = $controller . "." . $action;63                        $route->controllerId = $controllerId;64                        $route->controllerName = $controller;65                        $route->actionId = $actionId;66                        $route->actionName = $action;67                        $route->actionType = ActionPermission::ACTION_TYPE_INLINE;68                        $route->controllerClass = $className;69                        $route->actionMethod = $method;70                        $route->file = $file;71                        $route->route = $controllerId . "/" .$actionId;72                        if (!$notExistedOnly || !$route->isExisted()) {73                            $res[] = $route;74                        }75                        Yii::info("Inline action found: " . $controllerId . "/" .$actionId);76                    }77                }78                $standaloneActions = $objInstance->actions();79//                VarDumper::dump($standaloneActions);80                if (!empty($standaloneActions)) {81                    foreach ($standaloneActions as $actionName => $actionConfig) {82                        $route = new ActionPermission();83                        $route->appAlias = $alias;84                        if (isset($actionConfig["class"])) {85                            $route->actionClass = $actionConfig["class"];86                        }87                        $route->name = $controller . "." . $actionName;88                        $route->actionType = ActionPermission::ACTION_TYPE_STANDALONE;89                        $route->controllerId = $controllerId;90                        $route->controllerName = $controller;91                        $route->actionId = $actionName;92                        $route->actionName = $actionName;93                        $route->controllerClass = $className;94                        $route->actionMethod = "";95                        $route->file = $file;96                        $route->route = $controllerId . "/" .$actionName;97                        if (!$notExistedOnly || !!$route->isExisted()) {98                            $res[] = $route;99                        }100//                        echo "Standalone action found: " . $controllerId . "/" . $actionName . "\n";101                    }102                }103            }104            else {105                Yii::info("Controller NOT found in $file");106            }107        }108        return $res;109    }110    /**111     * list route cua tat ca cac controller cua app chi dinh boi $alias112     * @param string $alias - application ('@backend', '@frontend', '@app', '@console'...), actions of which to be listed113     * @param bool $notExistedOnly114     * @return ControllerRole[]115     */116    public static function listControllers($alias = '@app', $notExistedOnly = false) {117        $res = [];118        $path = Yii::getAlias($alias) . "/controllers";119//        echo $path . "\n";120        $controllerFiles = glob($path . "/*Controller.php");121//        VarDumper::dump($controllerFiles);122        foreach ($controllerFiles as $file) {123            $h = fopen($file, 'r') or die('wtf');124            $ns = '';125            $class = '';126            while (!feof($h)) {127                $line = fgets($h);128                if (!$ns && strpos($line, 'namespace') !== false) {129                    $ns = trim(preg_replace('~\s*namespace\s+([\S]+).*~', '$1', $line));130                }131                if (!$class && strpos($line, 'class') !== false) {132                    $class = trim(preg_replace('/\s*class\s+(\w+).+/', '$1', $line));133                }134                if (!empty($ns) && !empty($class)) {135                    break;136                }137            }138            fclose($h);139            if (!empty($ns) && !empty($class)) {140                $ns = StringUtils::removeTail($ns, ";"); // bo dau ; cuoi cung )neu co141                $className = $ns . '\\' . $class;142                $controller = StringUtils::removeTail($class, "Controller");143                $controllerId = StringUtils::camel2Dash($controller);144                Yii::info("Controller found: " . $className . " (in $file)");145                $route = new ControllerRole();146                $route->appAlias = $alias;...HitHighlighter.php
Source:HitHighlighter.php  
...112            return $tweet;113        }114        $highlightTweet = '';115        $tags = array('<' . $this->tag . '>', '</' . $this->tag . '>');116        # Check whether we can simply replace or whether we need to chunk...117        if (strpos($tweet, '<') === false) {118            $ti = 0; // tag increment (for added tags)119            $highlightTweet = $tweet;120            foreach ($hits as $hit) {121                $highlightTweet = StringUtils::substrReplace($highlightTweet, $tags[0], $hit[0] + $ti, 0);122                $ti += StringUtils::strlen($tags[0]);123                $highlightTweet = StringUtils::substrReplace($highlightTweet, $tags[1], $hit[1] + $ti, 0);124                $ti += StringUtils::strlen($tags[1]);125            }126        } else {127            $chunks = preg_split('/[<>]/iu', $tweet);128            $chunk = $chunks[0];129            $chunk_index = 0;130            $chunk_cursor = 0;...StringMaster.php
Source:StringMaster.php  
...57        return false === self::isEmpty($str);58    }59    /**60     * Replaces a `string` with another `string` inside a larger `string`, for61     * the first maximum number of values to replace of the search `string`.62     *63     *     StringUtils::replace(null, *, *, *)         // null64     *     StringUtils::replace('', *, *, *)           // ''65     *     StringUtils::replace('any', null, *, *)     // 'any'66     *     StringUtils::replace('any', *, null, *)     // 'any'67     *     StringUtils::replace('any', '', *, *)       // 'any'68     *     StringUtils::replace('any', *, *, 0)        // 'any'69     *     StringUtils::replace('abaa', 'a', null, -1) // 'abaa'70     *     StringUtils::replace('abaa', 'a', '', -1)   // 'b'71     *     StringUtils::replace('abaa', 'a', 'z', 0)   // 'abaa'72     *     StringUtils::replace('abaa', 'a', 'z', 1)   // 'zbaa'73     *     StringUtils::replace('abaa', 'a', 'z', 2)   // 'zbza'74     *     StringUtils::replace('abaa', 'a', 'z', -1)  // 'zbzz'75     *76     * @param string $text The `string` to search and replace in.77     * @param string $search The `string` to search for.78     * @param string $replace The `string` to replace $search with.79     * @param integer $max The maximum number of values to replace, or `-1`80     *                         if no maximum.81     *82     * @return string The text with any replacements processed or `null` if83     *    `null` `string` input.84     */85    public static function replace($text, $search, $replace, $max = -1)86    {87        if (true === self::isEmpty($text) || true === self::isEmpty($search) || null === $replace || (0 === $max)) {88            return $text;89        }90        return \preg_replace('/' . \preg_quote($search, '/') . '/', $replace, $text, $max);91    }92    /**93     * Determine if a given string starts with a given substring.94     *95     * @param  string $haystack96     * @param  string|array $needles97     * @return bool98     */99    public static function startsWith($haystack, $needles)100    {101        foreach ((array)$needles as $needle) {102            if ($needle !== '' && substr($haystack, 0, strlen($needle)) === (string)$needle) {103                return true;104            }105        }106        return false;107    }108    /**109     * Determine if a given string ends with a given substring.110     *111     * @param  string $haystack112     * @param  string|array $needles113     * @return bool114     */115    public static function endsWith($haystack, $needles)116    {117        foreach ((array)$needles as $needle) {118            if (substr($haystack, -strlen($needle)) === (string)$needle) {119                return true;120            }121        }122        return false;123    }124    /**125     * Convert the given string to lower-case.126     *127     * @param  string $value128     * @return string129     */130    public static function lower($value)131    {132        return mb_strtolower($value, 'UTF-8');133    }134    /**135     * Convert the given string to upper-case.136     *137     * @param  string $value138     * @return string139     */140    public static function upper($value)141    {142        return mb_strtoupper($value, 'UTF-8');143    }144    /**145     * Return the length of the given string.146     *147     * @param  string $value148     * @param  string $encoding149     * @return int150     */151    public static function length($value, $encoding = null)152    {153        if ($encoding) {154            return mb_strlen($value, $encoding);155        }156        return mb_strlen($value);157    }158    /**159     * Convert a string to snake case.160     *161     * @param  string $value162     * @param  string $delimiter163     * @return string164     */165    public static function snake($value, $delimiter = '_')166    {167        $key = $value;168        if (isset(static::$snakeCache[$key][$delimiter])) {169            return static::$snakeCache[$key][$delimiter];170        }171        if (!ctype_lower($value)) {172            $value = preg_replace('/\s+/u', '', ucwords($value));173            $value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1' . $delimiter, $value));174        }175        return static::$snakeCache[$key][$delimiter] = $value;176    }177    /**178     * Returns the portion of string specified by the start and length parameters.179     *180     * @param  string $string181     * @param  int $start182     * @param  int|null $length183     * @return string184     */185    public static function substr($string, $start, $length = null)186    {187        return mb_substr($string, $start, $length, 'UTF-8');...StringUtilsTest.php
Source:StringUtilsTest.php  
...89    {90        $string = 'I went to {{place}}';91        $data = ['place' => 'Portland'];92        $expected = 'I went to Portland';93        $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data));94        $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_DOUBLE_MUSTACHE));95        $string = 'I went to %{place}';96        $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_PERCENTAGE_MUSTACHE));97        $string = 'Took a flight from {{from_airport}} to {{to_airport}}';98        $data = ['from_airport' => 'SFO', 'to_airport' => 'PDX'];99        $expected = 'Took a flight from SFO to PDX';100        $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data));101        $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_DOUBLE_MUSTACHE));102        $string = 'Took a flight from %{from_airport} to %{to_airport}';103        $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_PERCENTAGE_MUSTACHE));104        $string = 'Paid: {{true}},  overdue: {{false}}.';105        $data = ['true' => true, 'false' => false];106        $expected = 'Paid: true,  overdue: false.';107        $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_DOUBLE_MUSTACHE));108    }109    public function testCsv()110    {111        $csv = 'one, two, , three,four';112        // trim string113        $result = StringUtils::csv($csv);114        $this->assertInternalType('array', $result);115        $this->assertCount(5, $result);116        $this->assertSame('two', $result[1]);117        // without trim118        $result = StringUtils::csv($csv, false);119        $this->assertInternalType('array', $result);120        $this->assertCount(5, $result);121        $this->assertSame(' two', $result[1]);...replace
Using AI Code Generation
1$mystring = "Hello World";2echo StringUtils::replace($mystring,"World","Universe");3$mystring = "Hello World";4echo StringUtils::replace($mystring,"World","Universe");5$mystring = "Hello World";6echo StringUtils::replace($mystring,"World","Universe");7$mystring = "Hello World";8echo StringUtils::replace($mystring,"World","Universe");9$mystring = "Hello World";10echo StringUtils::replace($mystring,"World","Universe");11$mystring = "Hello World";12echo StringUtils::replace($mystring,"World","Universe");13$mystring = "Hello World";14echo StringUtils::replace($mystring,"World","Universe");15$mystring = "Hello World";16echo StringUtils::replace($mystring,"World","Universe");17$mystring = "Hello World";18echo StringUtils::replace($mystring,"World","Universe");19$mystring = "Hello World";20echo StringUtils::replace($mystring,"World","Universe");21$mystring = "Hello World";22echo StringUtils::replace($mystring,"World","Universe");23$mystring = "Hello World";24echo StringUtils::replace($mystring,"World","Universe");25$mystring = "Hello World";26echo StringUtils::replace($mystring,"World","Universe");replace
Using AI Code Generation
1require_once 'lib/StringUtils.php';2$string = 'hello world';3echo StringUtils::replace($string, 'hello', 'hi');4require_once 'lib/StringUtils.php';5$string = 'hello world';6echo StringUtils::replace($string, 'hello', 'hi');7require_once 'lib/StringUtils.php';8$string = 'hello world';9echo StringUtils::replace($string, 'hello', 'hi');10require_once 'lib/StringUtils.php';11$string = 'hello world';12echo StringUtils::replace($string, 'hello', 'hi');13require_once 'lib/StringUtils.php';14$string = 'hello world';15echo StringUtils::replace($string, 'hello', 'hi');16require_once 'lib/StringUtils.php';17$string = 'hello world';18echo StringUtils::replace($string, 'hello', 'hi');19require_once 'lib/StringUtils.php';20$string = 'hello world';21echo StringUtils::replace($string, 'hello', 'hi');22require_once 'lib/StringUtils.php';23$string = 'hello world';24echo StringUtils::replace($string, 'hello', 'hi');25require_once 'lib/StringUtils.php';26$string = 'hello world';27echo StringUtils::replace($string, 'hello', 'hi');28require_once 'lib/StringUtils.php';29$string = 'hello world';30echo StringUtils::replace($string, 'hello', 'hi');31require_once 'lib/StringUtils.php';32$string = 'hello world';33echo StringUtils::replace($string, 'hello', 'hi');34require_once 'lib/StringUtils.php';35$string = 'hello world';replace
Using AI Code Generation
1require_once 'StringUtils.php';2$string = new StringUtils();3echo $string->replace("This is a string","string","text");4require_once 'StringUtils.php';5$string = new StringUtils();6echo $string->replace("This is a string","is","was");7require_once 'StringUtils.php';8$string = new StringUtils();9echo $string->replace("This is a string","is","was",1);10require_once 'StringUtils.php';11$string = new StringUtils();12echo $string->replace("This is a string","is","was",2);13require_once 'StringUtils.php';14$string = new StringUtils();15echo $string->replace("This is a string","is","was",3);16require_once 'StringUtils.php';17$string = new StringUtils();18echo $string->replace("This is a string","is","was",4);19require_once 'StringUtils.php';20$string = new StringUtils();21echo $string->replace("This is a string","is","was",5);22require_once 'StringUtils.php';23$string = new StringUtils();24echo $string->replace("This is a string","is","was",6);25require_once 'StringUtils.php';26$string = new StringUtils();27echo $string->replace("This is a string","is","was",7);replace
Using AI Code Generation
1require_once 'StringUtils.php';2$utils = new StringUtils();3echo $utils->replace('Hello World', 'World', 'India');4require_once 'StringUtils.php';5$utils = new StringUtils();6echo $utils->replace('Hello 1', '1', 2);7require_once 'StringUtils.php';8$utils = new StringUtils();9echo $utils->replace('Hello World', 'World', '!');10require_once 'StringUtils.php';11$utils = new StringUtils();12echo $utils->replace('Hello World', 'World', '!');13require_once 'StringUtils.php';14$utils = new StringUtils();15echo $utils->replace('Hello World', 'World', '!');16require_once 'StringUtils.php';17$utils = new StringUtils();18echo $utils->replace('Hello World', 'World', '!');19require_once 'StringUtils.php';20$utils = new StringUtils();21echo $utils->replace('Hello World', 'World', '!');22require_once 'StringUtils.php';23$utils = new StringUtils();24echo $utils->replace('Hello World', 'World',Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Execute automation tests with replace on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.
Test now for FreeGet 100 minutes of automation test minutes FREE!!
