preg_replace doesn't work - php

I've small preg_replace problem. I need to resize iframe code output so I'm using preg_replace, regex seems to work fine, but result is same as input no changes. Here code I'm using:
$video_code = preg_replace( '/width="(.*?)"/', 'width="'.$width.'"', $video_code );
$video_code = preg_replace( '/height="(.*?)"/', 'height="'.$height.'"', $video_code );
This iframe that $video_code contains:
<iframe class='sproutvideo-player' type='text/html' src='http://videos.sproutvideo.com/embed/189bd8b4191ee1c390/d0dc5859e1d409ed?type=hd&regularColors0=666565&regularColors1=595756&hoverColors0=ed2409&hoverColors1=d1390f&highlightColors1=c9c3c9&noBigPlay=true' width='768' height='432' frameborder='0'></iframe>
Any idea why is this happening?
Thanks
George

Try this:
$video_code = preg_replace ('/(width=[\'"])(.*?)([\'"])/', '$1620$3', $video_code);
$video_code = preg_replace ('/(height=[\'"])(.*?)([\'"])/', '$1' . $height . '$3', $video_code);
Escaped some characters and you're replacing everything inbetween the (), so the text height= in the replacement pattern is unnecessary.

I used your code and it worked fine for me. (made a few small changes, but not much)
Here is the code i used:
http://codepad.viper-7.com/fafGYW
Hope this helps.

$video_code = preg_replace('/width=[\'"][^\'"]+[\'"]/', 'width="'.$width.'"', $video_code);
$video_code = preg_replace('/height=[\'"][^\'"]+[\'"]/', 'height="'.$height.'"', $video_code);

Related

use php preg_replace to replace alt="20x20" with style="width:20;height:20;"

How would I use php preg_replace to parse a string of HTML and replace
alt="20x20" with style="width:20;height:20;"
Any help is appreciated.
I tried this.
$pattern = '/(<img.*) alt="(\d+)x(\d+)"(.*style=")(.*)$/';
$style = '$1$4width:$2px;height:$3px;$5';
$text = preg_replace($pattern, $style, $text);
You don't need preg_replace to do this. You can use str_replace
$html = '<img alt="20x20" />';
preg_match('/<img.*?alt="(.*?)".*>/',$html,$match);
$search = 'alt="' . $match[1] . '"';
list($width, $height) = explode('x', $match[1]);
if(is_numeric($width) && is_numeric($height))
{
$replace = 'style="width:' . $width . 'px;height:' . $height . 'px;"';
echo str_replace($search, $replace, $html);
}
Output:
<img style="width:20px;height:20px;">
If you insist on using regular expressions to alter HTML markup you'll no doubt get stuck sometime, at which point you'd do well to look into something like Python's beautiful soup, or possibly the goode olde tidy library, which I think comes included as part of the PHP spec. But for now:
<?php
$originalString = 'Your string containing <img src="xyz.png" alt="20x20">';
$patternToFind = '/alt="20x20"/i';
$replacementString = 'style="width:20;height:20;"';
preg_replace($patternToFind, $replacementString, $originalString);
?>
And since it seems a lot of people are mighty peeved at what seems to be a code request, you might check this link out for php.net's guidance. It's not always this clear in explaining PHP's constructs, but would have solved your problem easily in this case:
http://php.net/manual/en/function.preg-replace.php
As mentioned in the comments you should use DOM to manipulate HTML codes.
If you want to do this by preg_replace anyway, I'd suggest to find out the regex by yourself with the help of sites like this one.

How to use preg_replace to remove part of url address?

I have some HTML code like this:
<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf&sa=U&ei=sf0JUrmjIc3Nswb154CgDQ&ved=0CCkQFjAA&usg=AFQjCNGfXg_9x83U3pYr6JfkJcWuXv8X0Q">
I need to clean my code to get something like this
<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf">
using preg_replace.
My code is the following:
$serp = preg_replace('&sa=(.*)" ', '" ', $serp);
and it doesn't work.
BTW i need to restrict search with preg_replace until the FIRST entrance, i.e. i need to replace all html from &sa= to the FIRST ", but now it search from &sa= to the LAST "...
You're missing the regex delimiters.
$serp = preg_replace('/&sa=(.*)" /', '" ', $serp);
will give you this.
You missed the delimiter.
So your code looks like:
$serp = preg_replace('/&sa=(.*)" /', '" ', $serp);
okay, if you want to delete everything till the first quote then you can try the following instead of regex:
$temp = substr($serp,strpos($serp,'&sa='),strpos($serp,'"',strpos($serp,'&sa=')));
$serp = str_replace($temp,"",$serp);
Just another regex to do it :)
$text = '<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf&sa=U&ei=sf0JUrmjIc3Nswb154CgDQ&ved=0CCkQFjAA&usg=AFQjCNGfXg_9x83U3pYr6JfkJcWuXv8X0Q" target="_blank">';
$text = preg_replace('/(&sa=[^"]*)/', '', $text);
echo $text;
// Output:
<a href="http://mysite.com/documentos/Servicios/SUCRE/sucDoc19.pdf" target="_blank">
You can try it HERE (thks to hjpotter92 for this tool)

Regex to deterime text 'http://...' but not in iframes, embeds...etc

This regex is used to replace text links with a clickable anchor tag.
#(?<!href="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i
My problem is, I don't want it to change links that are in things like <iframe src="http//... or <embed src="http://...
I tried checking for a whitespace character before it by adding \s, but that didn't work.
Or - it appears they're first checking that an href=" doesn't already exist (?) - maybe I can check for the other things too?
Any thoughts / explanations how I would do this is greatly appreciated. Main, I just need the regex - I can implement in CakePHP myself.
The actual code comes from CakePHP's Text->autoLink():
function autoLinkUrls($text, $htmlOptions = array()) {
$options = var_export($htmlOptions, true);
$text = preg_replace_callback('#(?<!href="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i', create_function('$matches',
'$Html = new HtmlHelper(); $Html->tags = $Html->loadConfig(); return $Html->link($matches[0], $matches[0],' . $options . ');'), $text);
return preg_replace_callback('#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i',
create_function('$matches', '$Html = new HtmlHelper(); $Html->tags = $Html->loadConfig(); return $Html->link($matches[0], "http://" . $matches[0],' . $options . ');'), $text);
}
You can expand the lookbehind at the beginning of those regexes to check for src=" as well as href=", like this:
(?<!href="|src="|">)

How to remove a link from content in php?

How can i remove the link and remain with the text?
text text text. <br><a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>
like this:
text text text. <br>
i still have a problem.....
$text = file_get_contents('http://www.example.com/file.php?id=name');
echo preg_replace('#<a.*?>.*?</a>#i', '', $text)
in that url was that text(with the link) ...
this code doesn't work...
what's wrong?
Can someone help me?
I suggest you to keep the text in link.
strip_tags($text, '<br>');
or the hard way:
preg_replace('#<a.*?>(.*?)</a>#i', '\1', $text)
If you don't need to keep text in the link
preg_replace('#<a.*?>.*?</a>#i', '', $text)
While strip_tags() is capable of basic string sanitization, it's not fool-proof. If the data you need to filter is coming in from a user, and especially if it will be displayed back to other users, you might want to look into a more comprehensive HTML sanitizer, like HTML Purifier. These types of libraries can save you from a lot of headache up the road.
strip_tags() and various regex methods can't and won't stop a user who really wants to inject something.
Try:
preg_replace('/<a.*?<\/a>/','',"test test testa<br> <a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>");
this is my solutions :
function removeLink($str){
$regex = '/<a (.*)<\/a>/isU';
preg_match_all($regex,$str,$result);
foreach($result[0] as $rs)
{
$regex = '/<a (.*)>(.*)<\/a>/isU';
$text = preg_replace($regex,'$2',$rs);
$str = str_replace($rs,$text,$str);
}
return $str;}
A version from the above compiled notes:
$withoutlink = preg_replace('/<a.*>(.*)<\/a>/isU','$1',$String);
strip_tags() will strip HTML tags.
Try this one. Very simple!
$content = "text text text. <br><a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>";
echo preg_replace("/<a[^>]+\>[a-z]+/i", "", $content);
Output:
text text text. <br>
Try:
$string = preg_replace( '#<(a)[^>]*?>.*?</\\1>#si', '', $string );
Note:
this code remove link with text.
One more short solution without regexps:
function remove_links($s){
while(TRUE){
#list($pre,$mid) = explode('<a',$s,2);
#list($mid,$post) = explode('</a>',$mid,2);
$s = $pre.$post;
if (is_null($post))return $s;
}
}
?>

BB Code issue PHP

Alright so I am using a little bbcode function for a forum I have, working well, so if, in example, I put
[b]Text[/b]
it will print Text in bold.
My issue is, if I have that code:
[b]
Text[/b]
Well it will not work, and just print that as it's right now.
Here is an example of the function I am using:
function BBCode ($string) {
$search = array(
'#\[b\](.*?)\[/b\]#',
);
$replace = array(
'<b>\\1</b>',
);
return preg_replace($search , $replace, $string);
}
Then when echo'ing it:
.nl2br(stripslashes(BBCode($arr_thread_row[main_content]))).
So my question would be, what is necessary so the BBcode works with everything inside it, but no necessarily on the same line.
In example:
[b]
Text
[/b]
Would simply be
Text
Thank you for any help!
Alex
You need the multiline modifier, which makes your pattern something like #\[b\](.*?)\[/b\]#ms
(note the trailing m)
There is actually a pecl extension that parses BBcode, which would be faster and more secure than writing it from scratch yourself.
I use this... It should work.
$bb1 = array(
"/\[url\](.*?)\[\/url\]/is",
"/\[img\](.*?)\[\/img\]/is",
"/\[img\=(.*?)\](.*?)\[\/img\]/is",
"/\[url\=(.*?)\](.*?)\[\/url\]/is",
"/\[red\](.*?)\[\/red\]/is",
"/\[b\](.*?)\[\/b\]/is",
"/\[h(.*?)\](.*?)\[\/h(.*?)\]/is",
"/\[php\](.*?)\[\/php\]/is"
);
$bb2 = array(
'\\1',
'<img alt="" src="\\1"/>',
'<img alt="" class="\\1" src="\\2"/>',
'<a rel="nofollow" target="_blank" href="\\1">\\2</a>',
'<span style="color:#ff0000;">\\1</span>',
'<span style="font-weight:bold;">\\1</span>',
'<h\\1>\\2</h\\3>',
'<pre><code class="php">\\1</code></pre>'
);
$html = preg_replace($bb1, $bb2, $html);

Categories