PHP- preg_replace on hex char - php

i have a string, like this:
'<indirizzo>Via Universit\E0 4</indirizzo>'
Whit HEX char... i need string become:
'<indirizzo>Via Università 4</indirizzo>'
So, i use:
$text= preg_replace('/(\\\\)([a-f0-9]{2})/imu', chr(hexdec("$2")), $text);
But dont work because hexdec dont use value of $2 (that is 'E0'), but use only value '2'.
So hexdex("2") is "2" and chr("2") isnt "à"
What can i do?

$text='<indirizzo>Via Universit\E0 4</indirizzo>';
function cb($match) {
return html_entity_decode('&#'.hexdec($match[1]).';');
}
$text= preg_replace_callback('/\\\\([a-f0-9]{2})/imu', 'cb', $text);
echo $text;

You need to specify your chr(hexdec()) as a callback. Just calling those functions and suppling the result as parameter to preg_replace doesn't do it.
preg_replace_callback('/\\\([a-f0-9]{2})/imu',
function ($match) { return chr(hexdec($match[1])); },
$text)
Having said that, there are probably better ways to do what you want to do overall.

You could also use
<?php
$str = preg_replace('/\\([a-f0-9]{2})/imue', '"\x$1"', '<indirizzo>Via Universit\E0 4</indirizzo>');

Related

replace multiple words that look the same in a string

I have a little problem in PHP.
$string = "[:string] has [:int] [:string] and [:int] [:string]";
I just wanna modify (probably with str_replace) it with:
$string = "He has 5 apples and 3 bananas";
How could I do that?
(Classic str_replace() will modify all [:int] with the same word,
and is not what I want).
Thank you very much...
You could use the following regex, to capture all groups to replace and then iterate over it.
\[:([^\]]+)\]
Or you can just use preg_replace_callback and pass an desired replace function to it.
$data = [...];
preg_replace_callback('/\[:([^\]]+)\]/', $str, function (&$matches) use ($data) {
return doSomethingWithMatches..
});

substr() to preg_replace() matches php

I have two functions in PHP, trimmer($string,$number) and toUrl($string). I want to trim the urls extracted with toUrl(), to 20 characters for example. from https://www.youtube.com/watch?v=HU3GZTNIZ6M to https://www.youtube.com/wa...
function trimmer($string,$number) {
$string = substr ($string, 0, $number);
return $string."...";
}
function toUrl($string) {
$regex="/[^\W ]+[^\s]+[.]+[^\" ]+[^\W ]+/i";
$string= preg_replace($regex, "<a href='\\0'>".trimmer("\\0",20)."</a>",$string);
return $string;
}
But the problem is that the value of the match return \\0 not a variable like $url which could be easily trimmed with the function trimmer().
The Question is how do I apply substr() to \\0 something like this substr("\\0",0,20)?
What you want is preg_replace_callback:
function _toUrl_callback($m) {
return "" . trimmer($m[0], 20) ."";
}
function toUrl($string) {
$regex = "/[^\W ]+[^\s]+[.]+[^\" ]+[^\W ]+/i";
$string = preg_replace_callback($regex, "_toUrl_callback", $string);
return $string;
}
Also note that (side notes wrt your question):
You have a syntax error, '$regex' is not going to work (they don't replace var names in single-quoted strings)
You may want to look for better regexps to match URLs, you'll find plenty of them with a quick search
You may want to run through htmlspecialchars() your matches (mainly problems with "&", but that depends how you escape the rest of the string.
EDIT: Made it more PHP 4 friendly, requested by the asker.

how can I add a function in the replacement of preg_replace in php?

This seems to work ok:
function findImageTags($string) {
$pattern = '/<div(.*?)sourcefile="([^"]+)"(.*?)>(.*?)<\/div>/s';
return preg_replace($pattern, $this->generateImage("$2"), $string);
}
function generateImage($url){
return $url;
}
But when in the generateImage function I try to do something with the argument I can't because the value of the argument is $2 instead of the real value.
So this doesn't work:
function generateImage($url){
$array = explode('.', $url);
return $array;
}
by the way replacing s with e in the pattern doesn't seem to work as I think it's deprecated.
So how can I manipulate the value of the argument in generateImage() ?
What you want is probably preg_replace_callback instead of preg_replace. Here you can use a function which returns the replacement value.
The way you coded it now, the $this->generateImage("$2") code is executed at the moment you call preg_replace. It's not passed as a callback, but instead it's executed first, and the output is passed as the callback.
If you want to execute that function, you have to pass the PHP code as a string, and use the e modifier (http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php for more info).
return preg_replace($pattern, '$this->generateImage("$2")', $string);
Or use preg_replace_callback() of course.

How do i encode all chars in a string

How do i encode all chars in a string.
Example :
A = %32 // Or something like that
B = %33
I want to do this without hardcoding every char. And i also want to be able to decode it again.
Is there a php function for this?
Thanks.
If you really want to do this, you could do it with preg_replace_callback quite easily:
echo preg_replace_callback('/./', function($char) {
return '%' . ord($char[0]);
}, 'this is probably an unnecessary step');
// %116%104%105%115%32%105%115%32%112%114%111%98%97%98%108%121%32%97%110%32%117%110%110%101%99%101%115%115%97%114%121%32%115%116%101%112
You could reverse it with the inverse, using chr:
echo preg_replace_callback('/%[^%]*/', function($seq) {
return chr(substr($seq[0], 1));
}, '%116%104%105%115');
// this
However, this is almost certainly unnecessary for whatever you're doing...
See:
chr
ord
preg_replace_callback
try with:
urlencode($string);
urldecode($string);
http://php.net/manual/en/function.urlencode.php
http://php.net/manual/en/function.urldecode.php
Don't you just mean ord() and chr() ?

Reverse String Using Regexes

If I had a string like <start_delim>asdf<end_delim> and I wanted to take an alphanumeric string between the delimiters and reverse it using regexes, how would I go about doing this?
My natural instinct was to use something like preg_replace("<start_delim>([a-zA-Z0-9]+)<end_delim>", strrev($1), $str), but for obvious reasons, that didn't work.
You'll have to use preg_replace_callback
$str = "<start_delim>asdf<end_delim>";
function my_callback($m) {
return $m[1].strrev($m[2]).$m[3];
}
echo preg_replace_callback("/(<start_delim>)([a-zA-Z0-9]+)(<end_delim>)/", 'my_callback' , $str);
http://codepad.org/xP2arFZk
Similar to previous solutions, but using a lambda:
$str = "<start_delim>asdf<end_delim>";
$result = preg_replace_callback('/<start_delim>([a-zA-Z0-9]+)<end_delim>/', function($matches) {
return strrev($matches[1]);
}, $str);
echo "$result\n";
Somebody pointed out in a comment it'd be better not to use the /e modifier, but
if possible, that would work. Almost exactly as you thought:
echo preg_replace('|<start_delim>([^<^]+)<end_delim>|e', 'strrev("$1")', $str);
Regards
rbo

Categories