Hello I'm trying to convert youtube links into embed code.
this is what I have:
<?php
$text = $post->text;
$search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*$#x';
$replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
$text = preg_replace($search, $replace, $text);
echo $text;
?>
It works for one link. However if I add two, it will only swap the last occurrence. What do I have to change?
You're not handling the end of the string properly. Remove the $, and replace it with the closing tag </a>. this will fix it.
$search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x';
$replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
$text = preg_replace($search, $replace, $text);
Try this : preg_replace($search, $replace, $text, -1);
I know it's the default but who knows...
EDIT Try that if not working ;
do{
$text = preg_replace($search, $replace, $text, -1, $Count);
}
while($Count);
Here are a regular expresion more efficient: http://pregcopy.com/exp/26, tralate this to PHP: (add "s" modifier)
<?php
$text = $post->text;
$search = '#<a (?:.*?)href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)([\w\-\_]+)["\\\']#ixs';
$replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></center>';
$text = preg_replace($search, $replace, $text);
echo $text;
?>
Test it
There are two types of youtube link for one video:
Example:
$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';
This function handles both:
function getYoutubeEmbedUrl($url)
{
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
The output of $link1 or $link2 would be the same :
$output1 = getYoutubeEmbedUrl($link1);
$output2 = getYoutubeEmbedUrl($link2);
// output for both: https://www.youtube.com/embed/NVcpJZJ60Ao
Now you can use the output in iframe!
Related
How to replace Instagram URLs from a text in embed format with regex?
//Input
$text = 'There is https://www.instagram.com/p/Bes0orNjOIa/?taken-by=kendalljenner and then there was https://www.instagram.com/p/BZMh9qgl8Kw/?taken-by=felix.gaebler';
//Expected output
$text = 'There is <iframe src="//www.instagram.com/p/Bes0orNjOIa/embed"></iframe> and then there was <iframe src="//www.instagram.com/p/BZMh9qgl8Kw/embed"></iframe>';
Regex is for matching Strings, not replacements or something similar.
If you want to convert your text into an embed link, this is a way to go:
<?php
$text = 'There is https://www.instagram.com/p/Bes0orNjOIa/?taken-by=kendalljenner and then there was https://www.instagram.com/p/BZMh9qgl8Kw/?taken-by=felix.gaebler';
$words = explode(' ', $text);
$output = array();
foreach ($words as $word) {
if(preg_match('/^https:\/\/www\.instagram\.com\/p\/.{6,}\?/', $word)) {
$code = explode("/", $word)[4];
$word = '<iframe src="//www.instagram.com/p/$code/embed"></iframe>';
}
array_push($output, $word);
}
echo implode(' ', $output);
?>
Output here: https://i.imgur.com/bHWKF6D.png
how to replace <p>hello</p> <p>world</p> to hello<br />world <br />
I've tried searching on stack but there is no matched result.
You could do this by using str_replace() function.
For instance:
$string = "<p>hello</p> <p>world</p>";
$string = str_replace('<p>', '', $string);
$string = str_replace('</p>', '<br />' , $string);
I try this myself and get what I expected
$pattern = '/<p>(\w+)\<\/p>/';
$subject = '<p>hello</p><p>world</p>';
$replacement = '${1}<br/>';
$out = preg_replace($pattern, $replacement, $subject);
I just wonder which is better regex or str_replace
I wrote a better solution, hope everybody can see it helpful and maybe improve it
$pattern = '/<p(.*?)>((.*?)+)\<\/p>/';
$replacement = '${2}<br/>';
$subject = 'html string';
$out = preg_replace($pattern, $replacement, $subject);
Use this to prevent breaking the first and last <p></p> :
$string = str_replace($string, '</p><p>', '');
But if a space comes between the tags, it won't work.
<?php
$str = '<p>hello</p> <p>world</p>';
$replaceArr = array('<p>', '</p>', '</p> <p>');
$replacementArr = array('', '', '<br />');
$str = str_replace($replaceArr, $replacementArr, $str);
echo $str;
?>
Try above code.
I currently have a code that finds and replaces urls into complete html links. It works fine but now i need to update it so that if there is image url then it should convert it into a html img tag and display it. Function im using now is...
function auto_link_text($text) {
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
return sprintf(\'<a rel="nowfollow" target="_blank" href="%s">%s</a>\', $url, $url);
');
return preg_replace_callback($pattern, $callback, $text);
}
Got it from...
How to add anchor tag to a URL from text input
Here is an example of the text i would to it to go through...
asdf
http://google.com/
asfd
http://yahoo.com/logo.jpg
http://www.apple.com/sdfsd.php?page_id=13&id=18210&status=active#1
http://youtube.com/logo.png
like it updated function to output...
asdf
<a rel="nowfollow" target="_blank" href="http://google.com/">http://google.com/</a>
asfd
<img src="http://yahoo.com/logo.jpg" class="example">
<a rel="nowfollow" target="_blank" href="http://www.apple.com/sdfsd.php?page_id=13&id=18210&status=active#1">http://www.apple.com/sdfsd.php?page_id=13&id=18210&status=active#1</a>
<img src="http://youtube.com/logo.png" class="example">
Big thanks in advance!
You can use this for example:
function create_anchor_tag($url, $text = false) {
if ($text===false) $text = $url;
return '<a rel="no-follow" target="_blank" href="' . $url . '">'
. $text . '</a>';
}
function create_image_tag($url) {
return '<img src="' . $url . '"/>';
}
function auto_link_text($text) {
$pattern = '~\b(?:(?:ht|f)tps?://|www\.)\S+(?<=[\PP?])~i';
$callback = function ($m) {
$img_ext = array('jpg', 'jpeg', 'gif', 'png');
$path = parse_url($m[0], PHP_URL_PATH);
$ext = substr(strrchr($path, '.'), 1);
if (in_array(strtolower($ext), $img_ext))
return create_image_tag($m[0]);
return create_anchor_tag($m[0]);
};
return preg_replace_callback($pattern, $callback, $text);
}
I used several functions to make it more clea[rn], but you can easily adapt it as you like.
Here is the nice post about the best suitable regex pattern for valid URL. I picked one from there to group all the URLs.
Online demo
Steps to follow:
simply extract the url.
put a check on the url and based on your own logic substitute the tag as shown in demo.
sample code: (get all the valid urls in groups. get it from index 1)
$re = "/(([A-Za-z]{3,9}:(?:\\/\\/)?(?:[-;:&=\\+\\$,\\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\\w]+#)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%#.\\w_]*)#?(?:[\\w]*))?)/";
$str = "...";
preg_match_all($re, $str, $matches);
sample code: (substitute anchor tag (or what ever you want to add))
$re = "/(([A-Za-z]{3,9}:(?:\\/\\/)?(?:[-;:&=\\+\\$,\\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\\w]+#)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%#.\\w_]*)#?(?:[\\w]*))?)/";
$str = "...";
$subst = '$1';
$result = preg_replace($re, $subst, $str);
function makeLinksInTheContent($html)
{
$html= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" rel=\"nofollow\" >$3</a>", $html);
$html= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" rel=\"nofollow\" >$3</a>", $html);
$html= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)#([\w\-]+\.([\w\-\.]+)+)/i", "$1$2#$3", $html);
return($html);
}
this is my code.
My need is autolinking the url. Using preg_replace to find the url and set link to this url.
for example: "A page contains www.google.com." if i pass this content to makeLinksInTheContent($html), it will return "A page contains www.google.com."
But The following url format is not getting linked.
(http://www.google.com)
www.test.com()and[]&^%$##!+|!##$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
http://www.test.com()and[]&^%$##!+|!##$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
https://www.test.com()and[]&^%$##!+|!##$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
ftp://www.test.com()and[]&^%$##!+|!##$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
I think my regular expression have some mistakes. please suggest us.
You can use preg_replace_callback in this case. Read more
Function
<?php
function replace_urls( $text = null ) {
$regex = '/((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/';
return preg_replace_callback( $regex, function( $m ) {
$link = $name = $m[0];
if ( empty( $m[1] ) ) {
$link = "http://".$link;
}
return ''.$name.'';
}, $text );
}
?>
Usage
<?php
$text = "http://stackoverflow.com/questions/17854971/preg-replace-to-replace-string-for-matching-url#17855054
www.google.com
https://twitter.com/
http://www.somelinkwithhash.com/post/4454/?foo=bar#foo=bar";
echo replace_urls( $text );
?>
Output
http://stackoverflow.com/questions/17854971/preg-replace-to-replace-string-for-matching-url#17855054
www.google.com
https://twitter.com/
http://www.somelinkwithhash.com/post/4454/?foo=bar#foo=bar
My answer to the last time you asked this:
preg_replace to replace string for matching url
I can suggest using my function - just tested with your data and works for me
function parse_links($string,$mailto=true)
{
$preg_r = "#(((https?|ftp)(://)?)?[a-zA-Z0-9-_.]{1,64}\.[a-zA-Z0-9-_.]{1,128}\.[a-z]{2,4}(\.[a-z]{2,4})?(/([^ ]{1,256}))?/?)#";
$string = preg_replace($preg_r,"$1",explode(" ",$string));
if($mailto)
{
$preg_r2 = "/([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z_\-\.][-\w]*[0-9a-zA-Z_\-\.]\.)+[a-zA-Z]{2,9})/";
$string = preg_replace($preg_r2,"$1",$string);
}
return implode(" ",$string);
}
Just pass false as second parameter if you don't want email links to be created
Based on a question I had answered here ( Use PHP to Replace HTML with HTML ), I'd like to be able to filter my output text for email addresses, and convert those text emails to "mailto" links.
Here's the PHP code that works, but only for converting some HTML to other HTML. What I've tried to do is have this function look for an email address, and convert it to a "mailto" link. For whatever reason, the code doesn't convert the email addresses. Here's my PHP:
function text_filter($string) {
$search = array('<p>__</p>', '/[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/');
$replace = array('<hr />', '$2');
$processed_string = str_replace($search, $replace, $string);
echo $processed_string;
}
When I use this function for output, this is what the code looks like:
<?php text_filter( get_the_content() ); ?>
str_replace() doesn't use regular expressions, rewritten with preg_replace().
Added delimiters to first matching expression.
Fixed replacement from $1 to $2.
function text_filter($string) {
$search = array('/<p>__<\/p>/', '/([a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/');
$replace = array('<hr />', '$1');
$processed_string = preg_replace($search, $replace, $string);
echo $processed_string;
}
#Adam Baney - This will work even when used repeatedly.
// EMAILS
$str = preg_replace('~(^|[\s\.,;\n\(])([a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})~',
'$1$2',
$str);
// PHONE NUMBERS
$str = preg_replace_callback('~(^|[\s\.,;\n\(])(?<! )([0-9 \+\(\)]{9,})~', function($m) {
return $m[1].''.$m[2].'';
}, $str);
You can't use str_replace to do a regular expression replace.
You will need to split the actions up.
function text_filter($string) {
$search = array('<p>__</p>');
$replace = array('<hr />');
$processed_string = str_replace($search, $replace, $string);
$processed_string = preg_replace('/[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/','$2',$processed_string);
echo $processed_string;
}
See: http://www.php.net/manual/en/function.preg-replace.php for preg replacing.
function obfuscate_email($content){
$pattern = '#([0-9a-z]([-_.]?[0-9a-z])*#[0-9a-z]([-.]?[0-9a-z])*\\.';
$pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
$replacement = '\\1';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
And add filter
add_filter( 'the_content', 'obfuscate_email' );
Another way to do it in order so that it would work with existing html links in text:
function html_parse_text($text)
{
$text = preg_replace("/(?<!\")(((f|ht){1}tps?:\/\/)[-a-zA-Z0-9#:%_\+.~#?&\/\/=]+)/",
'<a href="\\1" target=_blank>\\1</a>', $text);
$text = preg_replace("/([[:space:]()[{}])(www.[-a-zA-Z0-9#:%_\+.~#?&\/\/=]+)/",
'\\1<a href="http://\\2" target=_blank>\\2</a>', $text);
$text = preg_replace("/(?<!\")([_\.0-9a-z-]+#([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/",
'<a href="mailto:\\1" target=_blank>\\1</a>', $text);
return $text;
}
Here is another version of this that seems to work for me. I've added + char to handle "plus addressing" (like some+email#address.com)
function replaceemail($text) {-
$ex = "/([a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/";
preg_match_all($ex, $text, $url);
foreach($url[0] as $k=>$v) $text = str_replace($url[0][$k], ''.$url[0][$k].'', $text);
return $text;
}