Replace special characters the exact same way as Wordpress - php

I want to reformat the_title(); the exact same way as Wordpress does with the permalinks.
"Borislav Pekić" becomes "borislav-pekic", "Alberto Méndez" becomes "alberto-mendez" and so on.
<?php
$forfattare = the_title();
?>
I've tried to find the way Wordpress does it, but i can't find it. Thanks in advance.

I use this:
<?php function createAlias($name)
{
setlocale(LC_ALL, 'en_US.UTF8');
$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
$alias = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $name);
$alias = strtolower(trim($alias, '-'));
$alias = preg_replace("/[\/_|+ -]+/", "-", $alias);
while (substr($alias, -1, 1) == "-") {
$alias = substr($alias, 0, -1);
}
while (substr($alias, 0, 1) == "-") {
$alias = substr($alias, 1, 100);
}
return $alias;
}

Related

Extract Keywords from text php

I am trying to extract relative keywords from description input which use Wysiwyg, with multi language english/arabic… using the following function but its not doing the task I want. Have a look the function I am using:
function extractKeyWords($string) {
mb_internal_encoding('UTF-8');
$stopwords = array();
$string = preg_replace('/[\pP]/u', '', trim(preg_replace('/\s\s+/iu', '', mb_strtolower($string))));
$matchWords = array_filter(explode(' ',$string) , function ($item) use ($stopwords) { return !($item == '' || in_array($item, $stopwords)
|| mb_strlen($item) <= 2 || is_numeric($item));});
$wordCountArr = array_count_values($matchWords);
// <p><p>
arsort($wordCountArr);
return array_keys(array_slice($wordCountArr, 0, 10)); }
figured it out ! Thanks
function generateKeywords($str)
{
$min_word_length = 3;
$avoid = ['the','to','i','am','is','are','he','she','a','an','and','here','there','can','could','were','has','have','had','been','welcome','of','home',' ','“','words','into','this','there'];
$strip_arr = ["," ,"." ,";" ,":", "\"", "'", "“","”","(",")", "!","?"];
$str_clean = str_replace( $strip_arr, "", $str);
$str_arr = explode(' ', $str_clean);
$clean_arr = [];
foreach($str_arr as $word)
{
if(strlen($word) > $min_word_length)
{
$word = strtolower($word);
if(!in_array($word, $avoid)) {
$clean_arr[] = $word;
}
}
}
return implode(',', $clean_arr);
}
This one seems very nice and comprehensive https://www.beliefmedia.com.au/create-keywords
Just make sure to change this line
$string = preg_replace('/[^\p{L}0-9 ]/', ' ', $string);
to
$string = preg_replace('/[^\p{L}0-9 ]/u', ' ', $string);
To support other langages (e.g Arabic)
And also better to use mb_strlen
If the string is in html format you can add the
strip_tags($str);
Before
$min_word_length = 3;

Float conversion doesn't work

I have this function which I expected to work well for converting strings to floats:
function getFloat($value) {
$cleanString = preg_replace('/([^0-9\.,])/i', '', $value);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $value);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}
However:
$str = '449.0000';
echo getFloat($str);
// => 4490000
So I tried:
$str = '449.0000';
echo filter_var($str, FILTER_SANITIZE_NUMBER_FLOAT );
// => 4490000
Why does to they both convert 449.0000 to 449000?
The only thing that works here is (float) $str which returns 449 as expected but I need that function to get rid of alphabets spaces etc.
I like to use FILTER_VALIDATE_FLOAT
<?php
$str = '449.0000';
$filter = filter_var($str,FILTER_VALIDATE_FLOAT);
var_dump($filter);
if ($filter !== false) {
$float = floatval($filter);
var_dump($float);
}

PHP: remove word from sentence if it contains #

I want to remove words from sentence if word contains #, I am using php.
Input: Hi I am #RaghavSoni
Output: Hi I am
Thank You.
You could do:
$str = preg_replace('/#\w+/', '', $str);
This is not a good way, but it works :
<?php
$input="Hi I am #RaghavSoni";
$inputWords = explode(' ', $input);
foreach($inputWords as $el)
{
if($el[0]=="#" )
{
$input = str_replace($el, "", $input);
}
}
echo $input;
?>
while(strpos($string, '#') !== false) {
$location1 = strpos($string, "#");
$location2 = strpos($string, " ", $location1);
if($location2 !== false) {
$length = $location2 - $location1;
$string1 = substr($string, 0, $location1);
$string2 = substr($string, $location2);
$string = $string1 . $string2;
}
}
echo $string;
echo str_replace("#RaghavSoni", "", "Hi I am #RaghavSoni.");
# Output: Hi I am.

Php substr entire words

How can i substr 20 chars from $xbio and get only complete words?
$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'...';
TY
Found this searching stackoverflow - tell me what do you think please:
<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>
This is the function i always use:
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}
preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches);
echo $matches[1];
This is a function that i use for this kind of task:
function truncate($str, $maxLength, $append = '...') {
if (strlen($str) > $maxLength) {
$str = substr($str, 0, $maxLength);
$str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
$str = trim($str);
$str .= $append:
}
return $str;
}

How to remove all special characters from URL?

I have my class
public function convert( $title )
{
$nameout = strtolower( $title );
$nameout = str_replace(' ', '-', $nameout );
$nameout = str_replace('.', '', $nameout);
$nameout = str_replace('æ', 'ae', $nameout);
$nameout = str_replace('ø', 'oe', $nameout);
$nameout = str_replace('å', 'aa', $nameout);
$nameout = str_replace('(', '', $nameout);
$nameout = str_replace(')', '', $nameout);
$nameout = preg_replace("[^a-z0-9-]", "", $nameout);
return $nameout;
}
BUt I can't get it to work when I use special characters like ö and ü and other, can sombody help me here? I use PHP 5.3.
The first answer in this SO thread contains the code you need to do this.
And what about:
<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
From: http://php.net/manual/en/function.urlencode.php
I wrote this function a while ago for a project I was working on and couldn't get RegEx to work. Its not the best way, but it works.
function safeURL($input){
$input = strtolower($input);
for($i = 0; $i < strlen($input); $i++){
$working = ord(substr($input,$i,1));
if(($working>=97)&&($working<=122)){
//a-z
$out = $out . chr($working);
} elseif(($working>=48)&&($working<=57)){
//0-9
$out = $out . chr($working);
} elseif($working==46){
//.
$out = $out . chr($working);
} elseif($working==45){
//-
$out = $out . chr($working);
}
}
return $out;
}
Here's a function to help with what you're doing, it's written in
Czech: http://php.vrana.cz/vytvoreni-pratelskeho-url.php
(and translated to English)
Here's another take on it (from the Symfony documentation):
<?php
function slugify($text)
{
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
if (function_exists('iconv'))
{
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
if (empty($text))
{
return 'n-a';
}
return $text;
}

Categories