Using the Preg_Replace_Callback Function - php

Okay, I think the reason why the search bar on this page is broken is because the PHP updated, and preg_replace is deprecated. https://sparklewash.com/
I tried replacing the preg_replace function to preg_replace_callback like so, but I'm still getting some issues.
Original:
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
New Version:
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace_callback('/(^|_)([a-z])/',
create_function ('$matches', 'return strtoupper($matches[2]);'), $string); // Removes special chars.
}
I apologize if this is easy for you, I was trying to follow an article on here but I'm still relatively new to PHP.
Edit: I belive the preg_replace isn't what broke it due to some of the comments. I've made a new question here to stay on topic: Redirect Loop on $_GET Request

I would not recommend the syntax you are using, the most likely cause of the error, kindly try below syntax.
$result = preg_replace_callback('/(^|_)([a-z])/', function($matches){
return strtoupper($matches[0]);
/*
$matches[0] is the complete match of your regular expression
$matches[1] is the match of the 1st round brackets () similarly for $matches[2]...and so on.
*/
}, $string);
//Also $result will contain the resultant string
You have to just pass the $matched to your callback function, you can also declare the callback separately, as an stand alone function.
function make_upper($matches){
return strtoupper($matches[0]);
}
$result = preg_replace_callback('/(^|_)([a-z])/','make_upper' , $string);
Hope my solution works for you, Thanks. :)

Related

Get rid of multiple white spaces in php or mysql

I have a form which takes user inputs; Recently, I have come across many user inputs with multiple white spaces.
Eg.
"My tests are working fine!"
Is there any way I can get rid of these white spaces at PHP level or MySQL level?
Clearly trim doesn't work here.
I was thinking of using Recursive function but not sure if there's an easy and fast way of doing this.
my code so far is as below:
function noWhiteSpaces($string) {
if (!empty($string)) {
$string = trim($string);
$new_str = str_replace(' ', ' ', $string);
} else {
return false;
}
return $new_str;
}
echo noWhiteSpaces("My tests are working fine here !");
If the input is actual whitespaces and you want to replace them with a single space, you could use a regular expression.
$stripped = preg_replace('/\s+/', ' ', $input);
\s means 'whitespace' character. + means one or more. So, this replaces every instance of one or more whitespace characters' in $input with a single space. See the preg_replace() docs, and a nice tutorial on regexes.
If you're not looking to replace real whitespace but rather stuff like , you could do the same, but not with \s. Use this instead:
$stripped = preg_replace('/( )+/', ' ', $input);
Note how the brackets enclose .

regular expression in PHP to create wiki-style links

I'm developing a site which is going to use wiki-style links to internal content eg [[Page Name]]
I'm trying to write a regex to achieve this and I've got as far as turning it into a link and replacing spaces with dashes (this is our space substitute rather than underscores) but only for page names of two words.
I could write a separate regex for all likely numbers of words (say from 10 downwards) but I'm sure there must be a neater way of doing it.
Here's what I have at the moment:
$regex = "#[\[][\[]([^\s\]]*)[\s]([^\s\]]*)[\]][\]]#";
$description = preg_replace($regex,"$1 $2",$description);
If someone can advise me how I can modify this regex so it works for any number of words that would be really helpful.
You can use the preg_replace_callback() function which accepts a callback to process the replacement string. You can also use lazy quantifiers in the pattern instead of a lot of negations inside character classes.
The external preg_replace_callback will extract the matched text and pass it to the callback function, which will return the properly modified version.
$str = '[[Page Name with many words]]';
echo preg_replace_callback('/\[\[(.*?)\]\]/', 'parse_tags', $str);
function parse_tags($match) {
$text = $match[1];
$slug = preg_replace('/\s+/', '-', $text);
return "$text";
}
You should use a callback function to do the replacement (using preg_replace_callback):
$str = preg_replace_callback('/\[\[([^\]]+)\]\]/', function($matches) {
return '<a href="' . preg_replace('/\s+/', '-', $matches[1]) . '>' . $matches[1] . '</a>';
}, $str);

PHP regexp string to url problem [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I linkify urls in a string with php?
It would be so delightful if I could overcome this problem once and for all.
I need to able to create urls from strings like http://www.google.com and also www.google.com
function hyperlink($text)
{
// match protocol://address/path/
$text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "\\0", $text);
// match www.something
$text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1\\2", $text);
// return $text
return $text;
}
You will find many good answers in the php manual. Although the examples are mainly on this page, you should use preg_replace instead.
$text = preg_replace('![a-z]+://[a-z0-9_/.-]+!i', '$0', $text);
$text = preg_replace('!(^| )(www([a-z0-9_/.-]+)!i', '$1$2', $text);
Note: with preg you can use arbitrary delimiters, not just the standard / at the start and end of your expression. I used ! as it does not appear in the expression and this way you don't have to escape /. Also note that the i makes the expression case-insensitive so a-z is enough instead of a-zA-Z.
Alex: so let me get this right, you've got a string, be it anything, and you wish to convert all instances of a URL to a link with the URL within it?
What i dont get is that you've already got it working with the regex you're trying:
$string = "
<p>This string has http://www.google.com/ and has www.google.com it should match both</p>
";
$string = preg_replace("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i","<a href='$0'>$0</a>", $string);
echo $string;
will convert both URLs to be links as expected. I've not made any changes.
I'm thinking i'm missing what you mean, maybe you could paste some errors so we can see what the problem really is.
function hyperlink($text)
{
// match protocol://address/path/
$text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "\\0", $text);
// match www.something
$text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-])*)", "\\1\\2", $text);
// return $text
return $text;
}
I've just tested your solution and it works a treat, except for when you have a query string. e.g. www.example.com/search.php?q=ipod+nano&something=nothing will not get translated correctly.
I've made the relevant changes to your function below, this should now work more consistantly
function hyperlink($text)
{
// match protocol://address/path/
$text = ereg_replace("[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*", "\\0", $text);
// match www.something
$text = ereg_replace("(^| )(www([.]?[a-zA-Z0-9_/-\?&=\+%])*)", "\\1\\2", $text);
// return $text
return $text;
}
Just so you know i added: \?&=+% to the second regex.
You should test this across many more URL combinations.
But this should suffice for now.

Masking all but first letter of a word using Regex

I'm attempting to create a bad word filter in PHP that will analyze the word and match against an array of known bad words, but keep the first letter of the word and replace the rest with asterisks. Example:
fook would become f***
shoot would become s**
The only part I don't know is how to keep the first letter in the string, and how to replace the remaining letters with something else while keeping the same string length.
$string = preg_replace("/\b(". $word .")\b/i", "***", $string);
Thanks!
$string = 'fook would become';
$word = 'fook';
$string = preg_replace("~\b". preg_quote($word, '~') ."\b~i", $word[0] . str_repeat('*', strlen($word) - 1), $string);
var_dump($string);
$string = preg_replace("/\b".$word[0].'('.substr($word, 1).")\b/i", "***", $string);
This can be done in many ways, with very weird auto-generated regexps...
But I believe using preg_replace_callback() would end up being more robust
<?php
# as already pointed out, your words *may* need sanitization
foreach($words as $k=>$v)
$words[$k]=preg_quote($v,'/');
# and to be collapsed into a **big regexpy goodness**
$words=implode('|',$words);
# after that, a single preg_replace_callback() would do
$string = preg_replace_callback('/\b('. $words .')\b/i', "my_beloved_callback", $string);
function my_beloved_callback($m)
{
$len=strlen($m[1])-1;
return $m[1][0].str_repeat('*',$len);
}
Here is unicode-friendly regular expression for PHP:
function lowercase_except_first_letter($s) {
// the following line SKIP the first word and pass it to callback func...
// \W it allows to keep the first letter even in words in quotes and brackets
return preg_replace_callback('/(?<!^|\s|\W)(\w)/u', function($m) {
return mb_strtolower($m[1]);
}, $s);
}

str_replace spaces with hyphens in A tag's name attribute

$string = preg_replace("#[name=([a-zA-Z0-9 .-]+)*]#",''."$1",$string);
This part of script doesn't work:
str_replace(' ', '-', "$1")
I need to replace " " with "-",
i also try preg_replace inside main preg_replace, str_ireplace also
But this is still don't working
The replacement is evaluated upfront and not on each replace. But you can do so by either using the e modifier in your regular expression:
$string = preg_replace("#\[name=([a-zA-Z0-9 .-]+)*]#e", '"<td>$1</td>"', $string);
Or by using preg_replace_callback:
function callbackFunction($match) {
global $front_page;
return '<td>'.$match[1].'</td>';
}
$string = preg_replace_callback("#\[name=([a-zA-Z0-9 .-]+)*]#", 'callbackFunction', $string);
I guess you will have to do it in two steps, since $1 cannot be used in str_replace(). $1 doesn’t really exist as a variable, it is only a placeholder in the replacement string.

Categories