PHP make links using preg_replace? [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
replace any url's within a string of text, to clickable links with php
Just a quick question, When I post links like http://www.buddyweb.me it will just appear like that but, but t's not automaticly linked. So how can I replace the http://www.buddyweb.me with Google
Any suggestions are apreciated, thanks :)

Jut like here
function clickable($url){
$url = str_replace("\\r","\r",$url);
$url = str_replace("\\n","\n<BR>",$url);
$url = str_replace("\\n\\r","\n\r",$url);
$in=array(
'`((?:https?|ftp)://\S+[[:alnum:]]/?)`si',
'`((?<!//)(www\.\S+[[:alnum:]]/?))`si'
);
$out=array(
'<a href="$1" rel=nofollow>$1</a> ',
'<a href="http://$1" rel=\'nofollow\'>$1</a>'
);
return preg_replace($in,$out,$url);
}

$replaced = preg_replace('/(http[s]?:\/\/[^\s]*)/i', '$1', $url);

No need for preg-replace, just concatenate varibles around your link.
<?
$yourlink = "http://www.buddyweb.me";
$yourDescriptor = "Google";
$linkedlink = "$yourDescriptor";
echo $linkedlink;
?>

echo preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?#\[\]+]*)(/[\w\#$%&~/.\-;:=,?#\[\]+]*)?)#is", "\\1\\2", $string);
I would consider this a complicated Regular Expression. However, if you're interested in learning more, I really liked getting started with this video http://www.youtube.com/watch?v=DRR9fOXkfRE

Call something that will return it how you like.
<?php
$link = "http://stackoverflow.com";
$name = "Stack Overflow";
echo href($link, $name);
function href($link, $name){
$link = "$name";
return $link;
}
?>

Related

Rewriting HTML anchor using str_replace and regex [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 3 years ago.
The following is automatically output via editor:
1001-web-file
I would like to add an ID:
<a id="replace" href="https://someurl.com/1001-web-file.pdf">1001-web-file</a>
Then use str_replace and a regular expression to find the anchors in question and replace with:
<img src="https://someurl.com/1001-web-file-pdf-290x300.jpg"/>
What I've managed to do is:
$replace = array(
'<a id="pdfthumb" href="' => '<img src="',
'.pdf">pdfthumb</a>' => '-pdf-290x300.jpg"/></br>'
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
This works to tear down the anchor tag and rebuild as an img. But I can't do much more. I played around with some regex to create a wildcard and realized I need to create a variable for the href to use when I rebuild the HTML, but I'm stuck.
Any insight is much appreciated :)
In your case, I think it should be easier if you do it on client side using javascript.
My background is not PHP but you can use the same pattern to test with your PHP code:
Input:
1001-web-file
Output:
<img src="https://someurl.com/1001-web-file-pdf-290x300.jpg"/>
var input = '1001-web-file';
var pattern = /href=\"(.+)\.pdf\"/;
var match = input.match(pattern)[1];
input = input.replace(/(<a.*>).*(<\/a>)/, '$1<img src="' + match + '-pdf-290x300.jpg">$2');
console.log(input)
Here is translated php code of Tan javascript answer
$input = '1001-web-file';
preg_match('/href="(.+)\.pdf"/', $input, $m);
$match = $m[1];
$input = preg_replace('/(<a.*>).*(<\/a>)/', '$1<img src="'. $match .'-pdf-290x300.jpg">$2', $input);
echo $input;

How to replace all matching regex of a sting in PHP [duplicate]

This question already has answers here:
Remove all html tags from php string
(9 answers)
Regex str_replace
(2 answers)
Closed 5 years ago.
sorry for not beeing able to put the title exactly what my question, I can't find a way to ask it.
So im trying to replace all ' in a text inside and replace it for ' in php
I have a variable $desc = "he's such a good person and he'll be very successfull";
and I'm trying to do the following
$desc = str_replace("'","'",$desc);
But no success is there a way to use regex in str_replace?
Yes it looks to be fine now... for some reason.
Is there a way to use regex for it?
for example to remove html tags from the text?
$desc = "<strong> he's such a good person </strong> <br /> he'll be very successfull";
$desc = str_replace("<*>"," ",$desc);
You may try to use the correct PHP function to do this job, so please take a look at : preg_replace doc.
In your case, you would like to use like this :
preg_replace('/'/', "'", $desc);
Take a look at this execution:
https://eval.in/800948
Does it have to be a regex because this is a lot simpler way to do it
$desc = "he's such a good person and he'll be very successfull";
$new = str_replace(''', "'", $desc);
echo $new;
RESULT:
he's such a good person and he'll be very successfull
You don't need to use regex as it will be more complex
use
$desc = "he's such a good person and he'll be very successfull";
$desc = str_replace("'","'",$desc);
echo "after replace :"." ".$desc;
it is more simpler :)

change youtube url to embed url in php

I found this code (Swap all youtube urls to embed via preg_replace()) to swap youtube urls (http://www.youtube.com/watch?v=CfDQ92vOfdc, or http://www.youtube.com/v/CfDQ92vOfdc) into youtube embed urls (http://www.youtube.com/embed/CfDQ92vOfdc) but it doesn't seem to be working? Any ideas? I don't know much about regular expression.
Here's the code:
$string = 'http://www.youtube.com/watch?v=CfDQ92vOfdc';
$search = '#<a (?:.*?)href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)([\w\-\_]+)["\\\']#ixs';
$replace = 'http://www.youtube.com/embed/$2';
$url = preg_replace($search,$replace,$string);
but it's still displaying as:
http://www.youtube.com/watch?v=CfDQ92vOfdc
instead of:
http://www.youtube.com/embed/CfDQ92vOfdc
Thanks in advance.
One problem is that your expression is expecting a-href tags around the address.
Another issue is that your $replace string is using single-quotes which will not parse $2.
This simpler expression should work:
$string = 'http://www.youtube.com/watch?v=CfDQ92vOfdc';
$search = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
$replace = "youtube.com/embed/$1";
$url = preg_replace($search,$replace,$string);
echo $url;
Either change
$string = 'http://www.youtube.com/watch?v=CfDQ92vOfdc';
to
$string = '<a href="http://www.youtube.com/watch?v=CfDQ92vOfdc" ></a>';
OR
$search = '#<a (?:.*?)href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)([\w\-\_]+)["\\\']#ixs';
to
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
If there is anyone who is still looking for a better straight up solution ,
here it is I just played with your code until it gave me an easy solution.
$string = $content;
$search = '/www.youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
$replace = "<iframe width='560' height='315' src='https://youtube.com/embed/$1' frameborder='0' allowfullscreen></iframe>
";
$content = preg_replace($search,$replace,$string);
NOTE: to choose how you want the links to be processed just edit the $search part,
if you will be processing from www.youtube.com it will be
$search = '/www.youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
else if you want it to process just youtube.com links just remove the www.
$search = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
here is a function i wrote that you echo out the result:
function youtube_url_to_embed($youtube_url) {
$search = '/youtube\.com\/watch\?v=([a-zA-Z0-9]+)/smi';
$replace = "youtube.com/embed/$1";
$embed_url = preg_replace($search,$replace,$youtube_url);
return $embed_url;
}

Check if a string had been hyperlinked

What regular expression should I use to detect is the text I want to hyperlink had been already hyperlinked.
Example:
I use
$text = preg_replace('/((http)+(s)?:\/\/[^<>\s]+)/i', '\\0', $text);
to link regular URL, and
$text = preg_replace('/[#]+([A-Za-z_0-9]+)/', '#\\1', $text);
to link Twitter handle.
I want to detect whether or not the text I'm going to hyperlink had been wrapped in already.
Maybe not an answer but another possible solution; You could also search to see if the starting a element exists
$text = 'here';
if (gettype(strpos($text, "<a")) == "integer"){
//<a start tag was found
};
or just strip all tags regardless and build the link anyway
$text = 'here';
echo '' . strip_tags($text) . '';
Simple, replace the regular URLs first, as it won't affect anything starting with an # cause no URL starts with an #. Then replace the twitter handles.
That way you don't need to detect if it's been hyperlinked already.
if (strpos($str, '<a ') !== FALSE) echo 'ok';
else echo 'error';
$html = 'Stephen Ou';
$str = 'Stephen Ou';
if (strlen(str_replace($str, '', $html)) !== strlen($html)) {
echo 'I got a feeling';
}

How do I auto convert an url into a hyper link in PHP?

I have a script that outputs status updates and I need to write a script that automatically changes something like www.example.com into a hyper link in a chunk of text like Twitter and Facebook do. What functions can I use for this in PHP? If you know a tutorial please post it.
$string = " fasfasd http://webarto.com fasfsafa";
echo preg_replace("#http://([\S]+?)#Uis", '<a rel="nofollow" href="http://\\1">\\1</a>', $string);
Output:
fasfasd <a rel="nofollow" href="http://webarto.com">webarto.com</a> fasfsafa
You can use a regex to replace the url with a link. Look at the answers on this thread: PHP - Add link to a URL in a string.
Great solution!
I wanted to auto-link web links and also to truncate the displayed URL text, because long URLs were breaking out of the layout on some platforms.
After much fiddling around with regex, I realised the solution is actually CSS - this site gives a simple solution using CSS white-space.
Here is the working Function
function AutoLinkUrls($str,$popup = FALSE){
if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches)){
$pop = ($popup == TRUE) ? " target=\"_blank\" " : "";
for ($i = 0; $i < count($matches['0']); $i++){
$period = '';
if (preg_match("|\.$|", $matches['6'][$i])){
$period = '.';
$matches['6'][$i] = substr($matches['6'][$i], 0, -1);
}
$str = str_replace($matches['0'][$i],
$matches['1'][$i].'</xmp><a href="http'.
$matches['4'][$i].'://'.
$matches['5'][$i].
$matches['6'][$i].'"'.$pop.'>http'.
$matches['4'][$i].'://'.
$matches['5'][$i].
$matches['6'][$i].'</a><xmp>'.
$period, $str);
}//end for
}//end if
return $str; }

Categories