Add hyperlinks to words in php - php

I have found this function on buildinternet.com.
function tag_it($text) {
$text = preg_replace("/:(\w+):/", '$1',$text);
return $text;
}
What it does is adding hyperlinks to words enclosed in ":" and the problem is that it works only with single words and it doesn`t work with words that has a single quote.
So if I do this,
$test = "one :word1:, :two words:, :this is a phrase:, this has a single quote :don't: or :don't forget:.";
echo tag_it($test);
only to the :word1: will be added a hyperlink, the rest will be ignored.
I don`t know too much php and I would appreciate if someone could make the function work with more than one word and with a single quote too.
Thank you!
Edit:
So I have tried the following to add a different link to words enclosed in "#"
function tag_it($text) {
$out = preg_replace_callback(
"/:([^\:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},
preg_replace_callback(
"/#([^\#]+)#/",
function($m1) {
$linkText1 = $m1[1];
$link1 = str_replace('"', '', $m1[1]);
$link1 = str_replace("'", "", $m1[1]);
$link1 = str_replace(" ", "_", $link1);
return ''.$linkText1.'';
},
$text
)
);
return $out;
}
$test = "one :word:, #two words#, :this is a phrase:, this has a single quote :don:'t or :don't forget:.";
echo tag_it($test);
and i get this
one word, two_words,_/" title="//www.example.com/blog/two_words/" title="two words" target="_blank">two words, " target="_blank">//www.example.com/blog/two_words/" title="two words" target="_blank">two words, this is a phrase, this has a single quote don't or don't forget:.
It seems to work for the 1st word enclosed in ":" and is trying to work with the words enclosed in "#" too but something is happening along the way and I can`t figure it out.
Any tip is really appreciated.
Thank you!

Change the crucial line in the function to the following:
$text = preg_replace("/:([^:]+):/", '$1', $text);

change this /:(\w+):/ to this /:([^:]+):/

Try this hope this simple one will help you out..
Regex: :([^\:]+):
:([^\:]+): it will match : then all till not : and then : in end
Try this code snippet here
<?php
ini_set('display_errors', 1);
$test = "one :word1:, :two words:, :this is a phrase:, this has a single quote :don't: or :don't forget:.";
echo tag_it($test);
function tag_it($text)
{
$text = preg_replace("/:([^\:]+):/", '$1', $text);
return $text;
}

I'll let you finish it off, above are all valid, but leave you with broken links, so building on them, I'd do something like:
function tag_it($text) {
$out = preg_replace_callback(
"/:([^:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', "", $m[1]);
$link = str_replace("'", "", $m[1]);
return ''.$linkText.'';
},
$text);
return $out;
}
You'll need to finish it off to replace spaces with - or _ or something but should be easy enough to work it out.

To answer to my "Edit:", I have figured out the problem.
Here is the full function
function tag_it($text) {
$out = preg_replace_callback(
"/:([^\:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$text
);
$out = preg_replace_callback(
"/#([^\#]+)#/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$out
);
$out = preg_replace_callback(
"/#([^\#]+)#/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return ''.$linkText.'';
},$out
);
return $out;
}
$test = "one :word:, #two words#, #this is a phrase#, this has a single quote #don't# or :don't forget:.";
echo tag_it($test);

Related

I have a problem creating a slug for the link. I want to show the numbers in the link

I have this code and it works without problems, but the numbers cannot be shown in the link. Can you help? Thank you
$title = ' domin name انا هنا & _ : 09.12.2022';
function slug($string) {
$regex = "/\.$/";
$regex = "/\.+$/";
$regex = "/[.*?:'!##$&-_ ]+$/";
$result = preg_replace($regex, "", $string);
$val= preg_replace('/\s+/u', '-', trim($result));
return strtolower($val);
}
$slugs = slug($title);
echo $slugs;
Here is something you might like to try
<?php
$title = ' domin name انا هنا & _ : 09.12.2022';
function slug($string) {
$regex = "/\.$/";
$regex = "/\.+$/";
// $regex = "/[.*?!##$&-_ ]+$/";
$result = preg_replace($regex, "", $string);
$val= preg_replace('/\s+/u', '', trim($result));
$val= preg_replace('/[.:_]+/u', '-', trim($val));
return strtolower($val);
}
echo slug($title);

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 :)

Combining multiple regular expressions into one

I'm filtering all user input to remove the following characters:
http://www.w3.org/TR/unicode-xml/#Charlist ("not suitable characters for use with markup").
So, I have this two functions:
if (!function_exists("mb_trim")) {
function mb_trim($str)
{
return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $str);
}
}
function sanitize($str)
{
// Clones of grave and accent
$str = preg_replace("/[\x{0340}-\x{0341}]+/u", "", $str);
// Obsolete characters for Khmer
$str = preg_replace("/[\x{17A3}]+/u", "", $str);
$str = preg_replace("/[\x{17D3}]+/u", "", $str);
// Line and paragraph separator
$str = preg_replace("/[\x{2028}]+/u", "", $str);
$str = preg_replace("/[\x{2029}]+/u", "", $str);
// BIDI embedding controls (LRE, RLE, LRO, RLO, PDF)
$str = preg_replace("/[\x{202A}-\x{202E}]+/u", "", $str);
// Activate/Inhibit Symmetric swapping
$str = preg_replace("/[\x{206A}-\x{206B}]+/u", "", $str);
// Activate/Inhibit Arabic from shaping
$str = preg_replace("/[\x{206C}-\x{206D}]+/u", "", $str);
// Activate/Inhibit National digit shapes
$str = preg_replace("/[\x{206E}-\x{206F}]+/u", "", $str);
// Interlinear annotation characters
$str = preg_replace("/[\x{FFF9}-\x{FFFB}]+/u", "", $str);
// Byte Order Mark
$str = preg_replace("/[\x{FEFF}]+/u", "", $str);
// Object replacement character
$str = preg_replace("/[\x{FFFC}]+/u", "", $str);
// Scoping for Musical Notation
$str = preg_replace("/[\x{1D173}-\x{1D17A}]+/u", "", $str);
$str = mb_trim($str);
if (mb_check_encoding($str)) {
return $str;
} else {
return false;
}
}
I have not much knowledge with regular expresions, so, what I want to know is
Is the mb_trim function correct for trimming multi-byte strings?
Is it possible to join all regular expresions in the function
sanitize to do only one preg_replace?
Thanks
You can do with one preg_replace by combining them into a one character set like so:
$str = preg_replace("/[\x{0340}-\x{0341}\x{17A3}\x{17D3}\x{2028}-\x{2029}\x{202A}-\x{202E}\x{206A}-\x{206B}\x{206C}-\x{206D}\x{206E}-\x{206F}\x{FFF9}-\x{FFFB}\x{FEFF}\x{FFFC}\x{1D173}-\x{1D17A}]+/u", "", $str);

PHP - a function to "sanitize" a string

is there any PHP function available that replaces spaces and underscores from a string with dashes?
Like:
Some Word
Some_Word
Some___Word
Some Word
Some ) # $ ^ Word
=> some-word
basically, the sanitized string should only contain a-z characters, numbers (0-9), and dashes (-).
This should produce the desired result:
$someword = strtolower(preg_replace("/[^a-z]+/i", "-", $theword));
<?php
function sanitize($s) {
// This RegEx removes any group of non-alphanumeric or dash
// character and replaces it/them with a dash
return strtolower(preg_replace('/[^a-z0-9-]+/i', '-', $s));
}
echo sanitize('Some Word') . "\n";
echo sanitize('Some_Word') . "\n";
echo sanitize('Some___Word') . "\n";
echo sanitize('Some Word') . "\n";
echo sanitize('Some ) # $ ^ Word') . "\n";
Output:
Some-Word
Some-Word
Some-Word
Some-Word
Some-Word
You might like to try preg_replace:
http://php.net/manual/en/function.preg-replace.php
Example from this page:
<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
//April1,2003
?>
You might like to try a search for "search friendly URLs with PHP" as there is quite a bit of documentation, example:
function friendlyURL($string){
$string = preg_replace("`\[.*\]`U","",$string);
$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');
$string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string );
$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);
return strtolower(trim($string, '-'));
}
and usage:
$myFriendlyURL = friendlyURL("Barca rejects FIFA statement on Olympics row");
echo $myFriendlyURL; // will echo barca-rejects-fifa-statement-on-olympics-row
Source: http://htmlblog.net/seo-friendly-url-in-php/
I found a few interesting solutions throughout the web.. note none of this is my code. Simply copied here in hopes of helping you build a custom function for your own app.
This has been copied from Chyrp. Should work well for your needs!
/**
* Function: sanitize
* Returns a sanitized string, typically for URLs.
*
* Parameters:
* $string - The string to sanitize.
* $force_lowercase - Force the string to lowercase?
* $anal - If set to *true*, will remove all non-alphanumeric characters.
*/
function sanitize($string, $force_lowercase = true, $anal = false) {
$strip = array("~", "`", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
"}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
"—", "–", ",", "<", ".", ">", "/", "?");
$clean = trim(str_replace($strip, "", strip_tags($string)));
$clean = preg_replace('/\s+/', "-", $clean);
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
EDIT:
Even easier function I found! Just a few lines of code, fairly self-explanitory.
function slug($z){
$z = strtolower($z);
$z = preg_replace('/[^a-z0-9 -]+/', '', $z);
$z = str_replace(' ', '-', $z);
return trim($z, '-');
}
Not sure why #Dagon chose to leave a comment instead of an answer, but here's an expansion of his answer.
php's preg_replace function allows you to replace anything with anything else.
Here's an example for your case:
$input = "a word 435 (*^(*& HaHa";
$dashesOnly = preg_replace("#[^-a-zA-Z0-9]+#", "-", $input);
print $dashesOnly; // prints a-word-435-HaHa;
You can think of writing this piece of code with the help of regular expressions.
But I dont see any available functions which help you directly replace the " " with "-"

Categories