PHP string class
The class will contain functions for multiple operations related to strings.
<?php
/**
* This class handles all kings of string processing.
* @package Sami's strings class
* @version $Id: samis_strings.php v.1.0 2018-02-01 13:41:00 $
* @author Samuil Banti
* @copyright (C) 2018 - Samuil Banti
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
class samis_strings {
/**
* Escapes the HTML entities of specific tag content.
* Useful for code formating.
* @param string $string - The string to escape.
* @param string $tag - The tag to convert
* @return string - The string with escaped tags content.
*/
public function escape_tag_content($string, $tag = 'pre')
{
if(preg_match_all("'<{$tag}(.*?)>(.*?)<\/{$tag}>'si", $string, $matches)) {
$escaped_content = array();
foreach($matches[2] as $k => $match) {
$escaped_content = str_replace($match, htmlentities($match), $matches[0][$k]);
$string = str_replace($matches[0][$k], $escaped_content, $string);
}
}
return $string;
}
/**
* Converts the URLs in a string into clickable links if they are not.
* @param string $string - The string with the URLs.
* @param string $href_tags - The tags to be added to the links.
* @return string - The string with the clickable links.
*/
public function urls_to_links($string, $href_tags = 'target="_blank"') {
$regex = "/[^\"'](http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(\/\S*)+?/";
if(preg_match($regex, $string, $matches)) {
$url = trim($matches[0], PHP_EOL);
return preg_replace($regex, '<a href="'.$url.'" '.$href_tags.'>'.$url.'</a> ', $string);
}
return $string;
}
/**
* Get the number of frequencies of each word in a text.
* NOTE: If the text contains tags they will be removed.
* @param string $text - The text that will be analysed.
* @return array - Array with words and the number of occurrences.
*/
function words_frequency($text)
{
$text = str_replace([PHP_EOL,'<'], [' ',' <'], $text);
$text = strip_tags($text);
$text = preg_replace('/[-?.!,{}()|;=+]/', '', $text);
$words_frequency = array();
$text = explode(' ', $text);
foreach($text as $v) {
$v = trim($v);
if(empty($v)) {
continue;
}
$v = mb_strtolower($v, 'utf-8');
if(array_key_exists($v, $words_frequency)) {
++$words_frequency[$v];
} else {
$words_frequency[$v] = 1;
}
}
arsort($words_frequency);
return $words_frequency;
}
}
Download...