Convert URL to Slug With PHP - php

I'm using the below code to try and convert to slug and for some reason it's not echoing anything. I know I'm missing something extremely obvious. Am I not calling the function?
<?php
$string = "Can't You Convert This To A Slug?";
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
echo $string;
}
?>

You are echoing after the code exit from function.
try like this:
function clean_string($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
$some = clean_string("Can't You Convert This To A Slug?");
echo $some;
Or like this:
function clean_me(&$string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
$some = "Can't You Convert This To A Slug?";
clean_me($some);
echo $some;

<?php
$string = "Can't You Convert This To A Slug?";
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
$string = clean($string);
echo $string;
?>

Related

PHP replace special characters from a string

I have clean function for remove special caracter from string but that function also removing Turkish caracter (ı,ğ,ş,ç,ö) from string
function clean($string) {
$string = str_replace(' ', ' ', $string);
$string = preg_replace('/[^A-Za-z0-9\-]/', ' ', $string);
return preg_replace('/-+/', '-', $string);
}
How can I fix it ?
Add those characters you want to keep to preg, also add Upper cases if neededç I edited your code:
function clean($string) {
$string = str_replace(' ', ' ', $string);
$string = preg_replace('/[^A-Za-z0-9\-ığşçöüÖÇŞİıĞ]/', ' ', $string);
return preg_replace('/-+/', '-', $string);
}
Test:
$str='Merhaba=Türkiye 12345 çok çalış another one ! *, !#_';
var_dump(clean($str));
//Output: string(57) "Merhaba Türkiye 12345 çok çalış another one "
You can use iconv to replacing special characters like à->a, è->e
<?php
$string = "ʿABBĀSĀBĀD";
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
// output: [nothing, and you get a notice]
echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
// output: ABBSBD
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
// output: ABBASABAD
// Yay! That's what I wanted!
?>
Credits:
https://gist.github.com/swas/10643194
#dmp y
#Nisse Engström
Maybe you can try:
function clean($string) {
$string = str_replace(' ', ' ', $string);
$string = preg_replace('/[^A-Za-z0-9ĞİŞığşçö\-]/', ' ', $string);
return preg_replace('/-+/', '-', $string);
}
Which special characters you want to replace?
Maybe be it'll be easier to change a paradigm of cleaning from everything except ... to something concrete.
<?php
function garbagereplace($string) {
$garbagearray = array('#','#','$','%','^','&','*');
$garbagecount = count($garbagearray);
for ($i=0; $i<$garbagecount; $i++) {
$string = str_replace($garbagearray[$i], '-', $string);
}
return $string;
}
echo garbagereplace('text##$text%^&*text');
?>

php regex prevent replacing $ symbol

I have a php function which generates tags from string:
function generate_tags($text)
{
$string = preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $text);
$string = preg_replace('/\s+/', ' ', $string);
$string = mb_strtolower($string, 'UTF-8');
$keywords = explode(' ', trim($string));
foreach($keywords as $key => $value)
{
if((strlen($value)) < 1)
{
unset($keywords[$key]);
continue;
}
}
$result = array_unique($keywords);
$result = array_values($result);
return $result;
}
The string is:
Ke$ha - We Are Who We Are (Cherry Cole Private Booty) Full Oficial Version
But it replaces $ symbol. How can I prevent $ symbol on my function?
Modify the first preg_replace to skip over $ as well:
$string = preg_replace('/[^\p{L}\p{N}\s$]/u', ' ', $text);
Modify the first preg_replace to skip over $ as well:$string = preg_replace('/[^\p{L}\p{N}\s$]/u', ' ', $text);
you just have to press the tick underneath the voting buttons.

PHP: Can I remove ‪ #‎ from string

I need to remove ‪#‎ from string. I found this method:
$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
It doesn't work for the Thai language. I want to remove like this:
from
‪#‎Apple‬ ‪#‎ผลไม้‬
to
#Apple #ผลไม้
I can not understand why str_replace() did not work for you. This will do the job:
function cleanString($string) {
$search = array('‪', '‎', '‬');
$replace = array('', '', '');
return str_replace($search, $replace, $string);
}
$string = '‪#‎Apple‬ ‪#‎ผลไม้‬';
echo $string . "\n";
echo cleanString($string) . "\n";
Output is:
‪#‎Apple‬ ‪#‎ผลไม้‬
#Apple #ผลไม้
Working example can be found at http://sandbox.onlinephpfunctions.com/code/bbdbdf0758e5ea06faf32281021ae859b6d75a51

Regular expression for finding multiple patterns from a given string

I am using regular expression for getting multiple patterns from a given string.
Here, I will explain you clearly.
$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag);
The above is my code.
Here, i am finding the space in a word and replacing the space with the special character what ever i need, right??
Now, I need a regular expression that gives me patterns like
about_us, about-us, aboutus as output if i give about us as input.
Is this possible to do.
Please help me in that.
Thanks in advance!
And finally, my answer is
$string = "contact_us";
$a = array('-','_',' ');
foreach($a as $b){
if(strpos($string,$b)){
$separators = array('-','_','',' ');
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/".$b."/", $sep, $string);
}
print_r($outputs);
}
}
exit;
You need to do a loop to handle multiple possible outputs :
$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
You can try without regex:
$string = 'about us';
$specialChar = '-'; // or any other
$newtag = implode($specialChar, explode(' ', $string));
If you put special characters into an array:
$specialChars = array('_', '-', '');
$newtags = array();
foreach ($specialChars as $specialChar) {
$newtags[] = implode($specialChar, explode(' ', $string));
}
Also you can use just str_replace()
foreach ($specialChars as $specialChar) {
$newtags[] = str_replace(' ', $specialChar, $string);
}
Not knowing exactly what you want to do I expect that you might want to replace any occurrence of a non-word (1 or more times) with a single dash.
e.g.
preg_replace('/\W+/', '-', $string);
If you just want to replace the space, use \s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
I am not sure that regexes are the good tool for that. However you can simply define this kind of function:
function rep($str) {
return array( strtr($str, ' ', '_'),
strtr($str, ' ', '-'),
str_replace(' ', '', $str) );
}
$result = rep('about us');
print_r($result);
Matches any character that is not a word character
$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);
in case its just that... you would get problems if it's a longer string :)

How can I replace ":" with "/" in slugify function?

I have a function which slugifies the text, it works well except that I need to replace ":" with "/". Currently it replaces all non-letter or digits with "-". Here it is :
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;
}
I made just a couple modifications. I provided a search/replace set of arrays to let us replace most everything with -, but replace : with /:
$search = array( '~[^\\pL\d:]+~u', '~:~' );
$replace = array( '-', '/' );
$text = preg_replace( $search, $replace, $text);
And later on, this last preg_replace was replacing our / with an empty string. So I permited foward slashes in the character class.
$text = preg_replace('~[^-\w\/]+~', '', $text);
Which outputs the following:
// antiques/antiquities
echo slugify( "Antiques:Antiquities" );

Categories