I have this code:
preg_match_all('#href="/mp3/(.*?).html#', $content, $salida);
and I need to replace "_" to " " (space) in output (array), something like this
$salida = str_replace('_', ' ', $salida);
obviously that code does not work
I think what you're looking for is preg_replace_callback
$salida = preg_replace_callback(
'(href="/mp3/.*?\.html)',
function($m) {return str_replace("_","",$m[0]);},
$content);
Related
I have this code to find and replace some string if it's between some {{ and }}.
$string = 'This is my {{important keyword}}.';
$string = preg_replace('/{{(.*?)}}/', '$1', $string);
return $string;
How I can change the $1 part to have something like this:
important keyword
So the href needs to have the match item converted like a slug (words separated with a dash, no accent or special char).
Thanks.
You have to use preg_replace_callback() to allow change on matches in a function.
See also use($url) to allow the function to access to the external variable.
Code:
$url = 'https://example.com';
$string = 'This is my {{important keyword}}.';
$string = preg_replace_callback('/{{(.*?)}}/', function($matches) use ($url) {
$newURL = $url . '/' . str_replace(' ', '-', $matches[1]);
return '' . htmlentities($matches[1]) . '';
}, $string);
echo $string;
Output:
This is my important keyword.
I need to remove # from string. I found this method:
$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
It doesn't work for the Thai language. I want to remove like this:
from
#Apple #ผลไม้
to
#Apple #ผลไม้
I can not understand why str_replace() did not work for you. This will do the job:
function cleanString($string) {
$search = array('', '', '');
$replace = array('', '', '');
return str_replace($search, $replace, $string);
}
$string = '#Apple #ผลไม้';
echo $string . "\n";
echo cleanString($string) . "\n";
Output is:
#Apple #ผลไม้
#Apple #ผลไม้
Working example can be found at http://sandbox.onlinephpfunctions.com/code/bbdbdf0758e5ea06faf32281021ae859b6d75a51
Using the following code:
$text = "أطلقت غوغل النسخة المخصصة للأجهزة الذكية العاملة بنظام أندرويد من الإصدار “25″ لمتصفحها الشهير كروم.ولم تحدث غوغل تطبيق كروم للأجهزة العاملة بأندرويد منذ شهر تشرين الثاني العام الماضي، وهو المتصفح الذي يستخدمه نسبة 2.02% من أصحاب الأجهزة الذكية حسب دراسة سابقة. ";
$tags = "غوغل, غوغل النسخة, كروم";
$tags = explode(",", $tags);
foreach($tags as $k=>$v) {
$text = preg_replace("/\b{$v}\b/u","$0",$text, 1);
}
echo $text;
Will give the following result:
I love PHP">love PHP</a>, but I am facing a problem
Note that my text is in Arabic.
The way is to do all in one pass. The idea is to build a pattern with an alternation of tags. To make this way work, you must before sort the tags because the regex engine will stop at the first alternative that succeeds (otherwise 'love' will always match even if it is followed by 'php' and 'love php' will never be matched).
To limit the replacement to the first occurence of each word you can remove tag from the array once it has been found and you test if it is always present in the array inside the replacement callback function:
$text = 'I love PHP, I love love but I am facing a problem';
$tagsCSV = 'love, love php, facing';
$tags = explode(', ', $tagsCSV);
rsort($tags);
$tags = array_map('preg_quote', $tags);
$pattern = '/\b(?:' . implode('|', $tags) . ')\b/iu';
$text = preg_replace_callback($pattern, function ($m) use (&$tags) {
$mLC = mb_strtolower($m[0], 'UTF-8');
if (false === $key = array_search($mLC, $tags))
return $m[0];
unset($tags[$key]);
return '<a href="index.php?s=news&tag=' . rawurlencode($mLC)
. '">' . $m[0] . '</a>';
}, $text);
Note: when you build an url you must encode special characters, this is the reason why I use preg_replace_callback instead of preg_replace to be able to use rawurlencode.
If you have to deal with an utf8 encoded string, you need to add the u modifier to the pattern and you need to replace strtolower with mb_strtolower)
the preg_split way
$tags = explode(', ', $tagsCSV);
rsort($tags);
$tags = array_map('preg_quote', $tags);
$pattern = '/\b(' . implode('|', $tags) . ')\b/iu';
$items = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$itemsLength = count($items);
$i = 1;
while ($i<$itemsLength && count($tags)) {
if (false !== $key = array_search(mb_strtolower($items[$i], 'UTF-8'), $tags)) {
$items[$i] = '<a href="index.php?s=news&tag=' . rawurlencode($tags[$key])
. '">' . $items[$i] . '</a>';
unset($tags[$key]);
}
$i+=2;
}
$result = implode('', $items);
Instead of calling preg_replace multiple times, call it a single time with a regexp that matches any of the tags:
$tags = explode(",", tags);
$tags_re = '/\b(' . implode('|', $tags) . ')\b/u';
$text = preg_replace($tags_re, '$0', $text, 1);
This turns the list of tags into the regexp /\b(love|love php|facing)\b/u. x|y in a regexp means to match either x or y.
I have a string like this:
$str = ':-:casperon.png:-: google.com www.yahoo.com :-:sample.jpg:-: http://stackoverflow.com';
and I need to replace urls from the $str, but not images like casperon.png.
I have tried the following regex for replacing urls.
$regex = '/((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/';
$str = preg_replace_callback( $regex, 'replace_url', $str);
and the php function like below.
function replace_url($m){
$link = $name = $m[0];
if ( empty( $m[1] ) ) {
$link = "http://".$link;
}
return ''.$name.'';
}
But it replaced the image as links. But I need the image as normal.Only the urls need to replace. So I put the images in between :-:image:-: the symbols. Can anyone help me..?
You can use this regex:
:-:.*?:-:\W*(*SKIP)(*F)|(?:(?:http|ftp|https)://)?[\w-]+(?:\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&\/~+#-])?
RegEx Demo
This regex works on the concept of first selecting the unwanted text betweem :-: and :-: and discarding it using (*SKIP)(*F) directives.
You can change your code like that, using filter_var to check the possible urls:
function replace_url($m){
$link = (empty($m[1])) ? 'http://' . $m[0] : $m[0];
if (!filter_var($link, FILTER_VALIDATE_URL))
return $m[0];
return '' . $m[0] . '';
}
$regex = '~((?:https?|ftp)://)?[\w-]+(?>\.[\w-]+)+(?>[.,]*(?>[\w#?^=%/\~+#;-]+|&(?:amp;)?)+)*~';
$str = preg_replace_callback( $regex, 'replace_url', $str);
I want to replace chr(10) with
with PHP within
<!CDATA[[Text
test
test]]>
But I'm very poor in REGEX.
$xml = "cc\n<!CDATA[[Text\ntest\ntest]]>\naa\nbb\n";
$callback = function($m) {
return '<!CDATA[[' . preg_replace("~" . chr(10) . "~s", '
', $m[1]) . ']]>';
};
echo preg_replace_callback('~<!CDATA\[\[(.+?)\]\]>~s', $callback, $xml);
p.s. you can probably do it without preg_replace_callback, but it looks nicer than to put all logic into preg_replace...
Why use RegEx?
$final = str_replace( chr(10), '
', $cdata );