PHP preg_replace with multiple token replacements - php

I have the following string ($line) in a PHP function.
$line='<span class="cooktime">25 Mins<span class="value-title" title="PT0H25M"></span></span><span class="preptime">30 Mins<span class="value-title" title="PT0H30M"></span></span>';
I would like to transform each span set to the following using preg_replace or any other approach:
$line='<span class="cooktime">25 Mins<span class="value-title" itemprop="cookTime" content="PT0H25M"></span></span><span class="preptime">30 Mins<span class="value-title" itemprop="prepTime" title="PT0H30M"></span></span>';
Essentially I'm adding itemprop property to span block and renaming title attribute to content.
How do I achieve this?
Thanks for your time, JK

Could try something like this? (not tested in PHP, but tested the RegEx using JavaScript and it seemed to work.)
preg_replace("^(.+)title(.+)$","$1itemprop=\"prepTime\" content$2",$line);

Have a try with:
$str = '<span class="cooktime">25 Mins<span class="value-title" title="PT0H25M"></span></span>';
$str = preg_replace('/" title="/', '" itemprop="prepTime" content="', $str);
echo $str,"\n";
output:
<span class="cooktime">25 Mins<span class="value-title" itemprop="prepTime" content="PT0H25M"></span></span>

OK - I figured out the answer. Thanks to Andrew & M42 for giving ideas. Here it is:
$line = preg_replace('/\ (.*?)class="preptime"(.*?)<span class="value-title" title(.*?)/i','$1class="preptime"$2<span class="value-title" itemprop="prepTime" content$3',$line);
$line = preg_replace('/\ (.*?)class="cooktime"(.*?)<span class="value-title" title(.*?)/i','$1class="cooktime"$2<span class="value-title" itemprop="cookTime" content$3',$line);

Related

preg_replace a hashtag that doesn't end with ;

I am currently using preg_replace to replace hashtags mentioned with html links like shown below. The issue is there is a possibility there will be html code as well being checked. So some css such as color: #000000; will force it to try convert that hex code into a link.
I basically need my regex to ignore doing any preg_replace if the last letter of a word is ;. Here's what I currently have:
$str = preg_replace('/#([a-zA-Z0-9!_%]+)/', '#$1', $str);
Example input: 'I like #action movies!'
Expected output: I like #action movies!'
I cannot use the end of the string to check this as chunks of text is checked at any given time so the string supplied could be #computer text text text #computer for instance.
Appreciate any assistance.
In your regex you can check if next to your hashtag there is a ;, non alphanumeric, end of line or end of string:
/#([a-zA-Z0-9!_%]+)([^;\w]{1}|$)/
Then use $1 and $2 accordingly
'#$1$2'
Your code will look like
$str = preg_replace('/#([a-zA-Z0-9!_%]+)([^;\w]{1}|$)/', '#$1$2',$str);
Here you can see some tests: https://regex101.com/r/yN4tJ6/65
Until a regEx guru come to your rescue (if ever...) and because you are in PHP; here is a solution with few lines of code.
$str="hi #def; #abc #ghi"; // just a test case (first one need be skipped)
if (preg_match_all('/#([a-zA-Z0-9!_%]+.?)/', $str,$m)){
foreach($m[1] as $k) if(substr($k,-1)!=';') {
$k=trim($k);
$str=str_replace("#$k","<a href='http://wxample.com/tags/$k'>#$k</a>",$str);
}
}
print "$str\n";
you can add a condition to check last string is ; or not and use it accordingly .
Example :
if (substr($str, -1)==';'){
//do nothing
}
else {
$str = preg_replace('/#([a-zA-Z0-9!_%]+)/', '#$1', $str);
}
Hope this help .
This regex should work:
#([\w!%]+(?=[\s,!?.\n]|$))
Demo: https://regex101.com/r/KrRiD3/2
Your PHP code:
$str = 'I like #strategy games #f1f1f1; #e2e2e2; #action games!';
$str = preg_replace('/#([\w!%]+(?=[\s,!?.\n]|$))/', '#$1', $str);
echo $str;
output:
I like #strategy games #f1f1f1; #e2e2e2; #action games!
Well, You can use below code, Actually I am new to regex so it is not that professional but it works, here it is
$data = "<p style='color:#00000;'>Heloo</p> #computer text text text #computer #say #goo1d #sd! #say_hello";
echo preg_replace("/(?<!\:)(\s+)\#([\w]+)(?!\;)/",'#$2',$data);
This expression I have use
/(?<!\:)(\s+)\#([\w]+)(?!\;)/
Output is
<p style='color:#00000;'>Heloo</p> #computer text text text #computer #say #goo1d #sd! #say_hello
I hope it helps someone.

How to replace b tag with # sign

I have a string that looks like this
$t="<b>vist</b>thank you for the follow.";
I am trying to remove the tag b and put an "#" instead of this tag.
I tried this
str_replace("<b></b>","#",$t);
but it doesn't replace the closing tag.
I don't know why it is not working may be there is something omitted in the code.
Try with
$search = array('&#60b&#62','&#60/b&#62');
$replace = '#';
echo str_replace($search, $replace, $t);
To replace multiple words using str_replace() function,
You can Try this
$t="<b>vist</b> thank you for the follow";
$pattern=array();
$pattern[0]="<b>";
$pattern[1]="</b>";
$replacement=array();
$replacement[0]="#";
$replacement[1]="";
echo str_replace($pattern,$replacement,$t);
View the Demo
Try with -
$t="&#60b&#62vist&#60/b&#62";
echo str_replace(array("&#60b&#62", "&#60/b&#62"),"#",$t);

Preg Pattern Finding

I want to parse a html content that have something like this:
<td class="s3_40">12,909</td>
i tried many regex to find string in between (12,909)
like : %<td class=\"s3_40\">(.*)</td>%
but i didn't find that .
Hope this can help:
$str = '<td class="s3_40">12,909</td>';
if (preg_match('#<td class="s3_40">(.*)</td>#s', $str, $matches)) {
var_dump($matches[1]);
}
If you must do it with a regex. You can try a pattern like this:
/<td[^>]*>(.*?)<\/td>/
Try this
#(?<=(s3_40">))([^<]+)(?=(</td>))#
Try doing it like this, just keep adding to s3_41, s3_42, etc to the class you need.
<?php
$s = '<td class="s3_40">12,909</td>';
$pat = '#<td class=".*(s3_40|s3_41).*".*?>(.*?)</td>#isU';
preg_match_all($pat,$s,$ms);
var_dump($ms);

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;
}
}
?>

How to remove a text from a variable? (php)

I have a variable $link_item, it's used with echo and gives the strings like
<span class="name">Google</span>http://google.com
How to remove "<span class="name">Google</span>" from string?
It should give just "http://google.com".
Heard it can be done with regex(), please help.
Without regex:
echo substr($link_item, stripos($link_item, 'http:'))
But this only works if the first part (i.e. <span class="name">Google</span>) never contains http:. If you can assure this: here you go :)
Reference: substr, stripos
Update:
As #Gordon points out in his comment, my code is doing the same as strstr() already does. I just put it here in case one does not read the comments:
echo strstr($link_item, 'http://');
$string = '<span class="name">Google</span>http://google.com';
$pieces = explode("</span>",$string);
//In case there is more than one span before the URL
echo $pieces[count($pieces) -1];
Solved:
$contents = '<span class="name">Google</span>http://google.com';
$new_text = preg_replace('/<span[^>]*>([\s\S]*?)<\/span[^>]*>/', '', $contents);
echo $new_text;
// outputs -> http://google.com
Don't use a regex. Use a HTML parser to extract only the text you want from it.
Made myself
$link_item_url = preg_replace('#<span[^>]*?>.*?</span>#si', '', $link_item);
This will remove any <span + something + </span> from variable $link_item.
Thanks for all.

Categories