How to convert preg_replace e modifier to pref_replace_callback [duplicate] - php

This question already has answers here:
Replace preg_replace() e modifier with preg_replace_callback
(3 answers)
Closed 6 years ago.
I use a preg_replace for replacing words in templates
echo preg_replace('~%(\w+)%~e', '$obj->$1', $template);
$obj is an array of searches, and $template is the file I am searching and replacing. So I am replacing keywords like %REPLACE%.
Now I don't really understand how it works, and apparently the e modifier has just been deprecated so I think I have to use the pref_replace_callback instead. We are upgrading to php7 soon and so I must replace this line in my code.
Now I have already looked on stack overflow and found answers to other peoples similar problems, unfortunately the answers don't help with this particular pattern. I don't understand how this works let alone how to get preg_replace_callback working. I have tried reading up on preg_replace, but really I don't understand how it works.
So I how do I change the above code to preg_replace_callback?
PS. I have searched for tutorials on preg_replace_callback, but nothing that explains what I have to do.
This is not a duplicate of that other question. It is a completely different preg_replace. The answer to the other question does not answer my question, and I have not got the know how to work it out, as I am not very good with the preg_replace keyword.

Pretty sure this will work:
echo preg_replace_callback('~%(\w+)%~',
function($m) use($obj) {
return $obj->{$m[1]};
},
$template);

Related

How can this ereg code possibly be updated to preg_match? [duplicate]

This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 2 years ago.
I have reviewed the answers to this out the wazoo. I've googled this the same.
I have a variable that works really great with php 5.4 ereg but fails miserably with the latest stuff.
ereg($user.$pass, preg_replace('/\s/', '', trim($_POST['user']).trim($_POST['pass'])))
I have tried the following with no joy:
preg_match('/^$user.$pass/',
preg_match('/{$user.$pass}/',
preg_match({$user.$pass},
preg_match('{$user.$pass}',
I don't know what to do. I've also tried rewriting the code to use different input lines, but to no avail.
Does the rest of the line need escaping as well?
Is it possible that this function just doesn't port easily into the latest php versions?
This is the complete line of code. It looks to see if a user and password match the user and password for this page and trims out spaces. (I probably should sanitize it outside of this if statement.) It also checks the SESSIONS status. It may be a bit ugly but it works great in 5.4:
elseif(((!empty($_POST['user']) and !empty($_POST['pass']) and ereg($user.$pass, preg_replace('/\s/', '', trim($_POST['user']).trim($_POST['pass'])))) or (isset($_SESSION['logged']) and ($_SESSION['logged'] === true) and isset($_SESSION['user']) and ($_SESSION['user'] == $user))) and ($_SESSION['attempts'] < 5))
ADDITIONAL: I found a way around the ereg or the preg_match. It works great.
The (main) usage difference between ereg() and preg_match is the delimiters.
So if your code was:
ereg($user.$pass, preg_replace('/\s/', '', trim($_POST['user']).trim($_POST['pass'])));
the new equivalent code should be:
preg_match('/'.$user.$pass.'/', preg_replace('/\s/', '', trim($_POST['user']).trim($_POST['pass'])));
Please note the lack of {, } or ^ in the first parameter of preg_match().

PHP to remove xml [duplicate]

This question already has answers here:
How to get the value of an attribute from XML file in PHP?
(4 answers)
Closed 6 years ago.
I need some help with a problem if possible.
<IndexFile index="dlc:blahblahblahblah.zip" version="1.19.0" />
How would I use php to remove everything in the above line of code except
blahblahblahblah.zip
Note: blahblah isn't actual name, the name changes; I just need to remove the xml on either side of the .zip file.
I've tried a few things like strip_tags() but nothing works up to now.
Your test string was
<IndexFile index="dlc:blahblahblahblah.zip" version="4.19.0" />
Your regex pattern should be : index="dlc:(.+?)".
Your answer is:
blahblahblahblah.zip
Try it out at https://regex101.com/
See this answer for greedy vs nongreedy matching: java-pattern-does-not-return-leftmost-match
Ideally, you have to use an XML parser to parse the file and use XPaths/looping to get that item.
If that is the only line, why can't you just use a Regex to extract the value? index="[a-zA-Z0-9_.-:]*" (or [a-zA-Z0-9_.-:]*.zip)?
Again, you need to think about the future impacts.

Can someone help me with my Regex to get the text in html code? [duplicate]

This question already has answers here:
Regex select all text between tags
(23 answers)
Closed 8 years ago.
I need get the text from text in the html code using regex in php code. But maybe it's seem I wrong somewhere in my code. Please can you help me fix my code. Thank you very much!
This is my regex pattern:
/<a\shref="\/vn\/tags\/.*">(?P<tags>.*)<\/a>/
And this is example subject:
<ul class="clearfix"><li><span class="tagBoxTitle">Từ khóa: </span></li><li>Thực phẩm, </li><li>giá-cả, </li><li>hàng-tiêu-dùng, </li><li>giảm-giá, </li><li>cước-vận-tải, </li><li>giá-xăng, </li><li>xăng-dầu, </li><li>hàng-hóa, </li><li>CPI, </li><li>Tết-nguyên-đán</li></ul>
Hope I can get an answer as soon as possible, thanks again!
Don't parse html with regex.
If you wanna regex solution then turn all the .* to .*? in-order to do a non-greedy match.
<a\shref="\/vn\/tags\/.*?">(?P<tags>.*?)<\/a>
DEMO

Need to replace deprecated ereg_replace [duplicate]

This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 9 years ago.
I am working for a non-profit and i'm not an expert in PHP.
I need to replace the following code:
$status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "\\0", $status);
When I attempt to modify it to preg_replace, I get an error every different way I try to exit the code.
This will do the job:
$statut = preg_replace('~[a-z]+://[^<>\s]+[\w/]~i', '$0', $statut);
But if the goal of this replacement is to keep all urls and transform them into links, you must change the pattern a little. And, why not, test them with filter_validate_url

PHP: Regular Expression to get a URL from a string [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Identifying if a URL is present in a string
Php parse links/emails
I'm working on some PHP code which takes input from various sources and needs to find the URLs and save them somewhere. The kind of input that needs to be handled is as follows:
http://www.youtube.com/watch?v=IY2j_GPIqRA
Try google: http://google.com! (note exclamation mark is not part of the URL)
Is http://somesite.com/ down for anyone else?
Output:
http://www.youtube.com/watch?v=IY2j_GPIqRA
http://google.com
http://somesite.com/
I've already borrowed one regular expression from the internet which works, but unfortunately wipes the query string out - not good!
Any help putting together a regular expression, or perhaps another solution to this problem, would be appreciated.
Jan Goyvaerts, Regex Guru, has addressed this issue in his blog. There are quite a few caveats, for example extracting URLs inside parentheses correctly. What you need exactly depends on the "quality" of your input data.
For the examples you provided, \b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&##/%=~_|$?!:,.]*[A-Z0-9+&##/%=~_|$] works when used in case-insensitive mode.
So to find all matches in a multiline string, use
preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
Why not try this one. It is the first result of Googling "URL regular expression".
((https?|ftp|gopher|telnet|file|notes|ms-help):((\/\/)|(\\\\))+[\w\d:##%\/;$()~_?\+-=\\\.&]*)
Not PHP, but it should work, I just slightly modified it by escaping forward slashes.
source

Categories