Disallow * in php Search - php

I want to suppress Searches on a database from users inputting (for example) P*.
http://www.aircrewremembered.com/DeutscheKreuzGoldDatabase/
I can't work out how to add this to the code I already have. I'm guessing using an array in the line $trimmed = str_replace("\"","'",trim($search)); is the answer, replacing the "\"" with the array, but I can't seem to find the correct way of doing this. I can get it to work if I just replace the \ with *, but then I lose the trimming of the "\" character: does this matter?
// Retrieve query variable and pass through regular expression.
// Test for unacceptable characters such as quotes, percent signs, etc.
// Trim out whitespace. If ereg expression not passed, produce warning.
$search = #$_GET['q'];
// check if wrapped in quotes
if ( preg_match( '/^(["\']).*\1$/m', $search ) === 1 ) {
$boolean = FALSE;
}
if ( escape_data($search) ) {
//trim whitespace and additional disallowed characters from the stored variable
$trimmed = str_replace("\"","'",trim($search));
$trimmed = stripslashes(str_ireplace("'","", $trimmed));
$prehighlight = stripslashes($trimmed);
$prehighlight = str_ireplace("\"", "", $prehighlight);
$append = stripslashes(urlencode($trimmed));
} else {
$trimmed = "";
$testquery = FALSE;
}
$display = stripslashes($trimmed);

You already said it yourself, just use arrays as parameters for str_repace:
http://php.net/manual/en/function.str-replace.php
$trimmed = str_replace( array("\"", "*"), array("'", ""), trim($search) );
Every element in the first array will be replaced with the cioresponding element from the second array.
For future validation and sanitation, you might want to read about this function too:
http://php.net/manual/en/function.filter-var.php

use $search=mysql_real_escape_string($search); it will remove all characters from $search which can affect your query.

Related

PHP match and replace whole word

Hi I am replacing certain names with different value . Here is values I am replacing "#size-name" and "#size" .But the problem is my code replacing only size first and note name for example
#size = "replaceword"
#size-name = "replaceword2"
But its replacing
#size ="replaceword"
#size-name = "replaceword2-name"
How can I replace whole word not part of it here is my code
$tempOutQuery = preg_replace("/(\b($key)\b)/i" , $value , $tempOutQuery);
$tempOutQuery= str_replace("#".$key ,$value ,$tempOutQuery);
both codes are not working
My Full Code
$val= "Hi I want #size dress which is #size-name";
$tempOutQuery = preg_replace("/(\b(size)\b)/i" ,"replaceword", $tempOutQuery);
$tempOutQuery = preg_replace("/(\b(size-name)\b)/i" ,"replaceword2", $tempOutQuery);
If you could make replace without using regulat expressions, then I would suggest using standart str_replace() with arrays:
$val= "Hi i want #size dress which is #size-name";
$search = array('size-name', 'size');
$replace = array('replaceword2', 'replaceword');
$result = str_replace($search, $replace, $val);
The order of search and replace Strings is important!
You should take care that you replace long search-strings first, and the short strings later.
Here's another option for you, using preg_replace_callback. It's actually very similar to Gennadiy's method. The only real difference is that it's using the preg aspect of PHP (and it's a lot more work). But it's another way to skin the proverbial cat.
<?php
// SET OUR DEFAULT STRING
$string = 'Hi I want #size suit which is #size-name';
// LOOK FOR EITHER size-name OR size AND IF YOU FIND IT ...
// RUN THE FUNCTION 'replace_sizes'
$string = preg_replace_callback('~#(size-name|size)~', 'replace_sizes', $string);
// PRINT OUT OUR MODIFIED STRING
print $string;
// THIS IS THE FUNCTION THAT WILL BE RUN EVERY TIME A MATCH IS FOUND
// EITHER 'size' OR 'size-name' WILL BE STORED IN $m[1]
function replace_sizes($m) {
// SET UP AN ARRAY THAT HAS OUR POTENTIAL MATCHES AS KEYS
// AND THE TEXT WE WANT TO REPLACE WITH AS THE VALUE
$size_text_array = array('size-name' => 'replaceword2', 'size' => 'replaceword');
// RETURN WHATEVER THE VALUE IS BASED ON THE KEY
return $size_text_array[$m[1]];
}
This will print out:
Hi I want replaceword suit which is replaceword2
Here is a working demo:
http://ideone.com/njNTbB
You can try pre_replace() to replace whole word from an item of an array in PHP a shown below.
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\band\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
See the entire post here

Concatenate variables in a regular expression string with preg_match()

I'm using preg_match() function which determines whether a function is executed.
if( preg_match( '/^([0-9]+,){0,3}[0-9]+$/', $string ) ) { ... }
However I have to use a integer variable and integrate it in the regular expression:
$integer = 4;
if( preg_match( '/^([0-9]+,){0,' . $integer . '}[0-9]+$/', $string ) ) { ... }
but it doesn't match when it should. How is it that I can't concatenate a variable in the regex string?
Edit:
strval($integer) has solved my problem. I had to convert the integer value into a string before concatenating it (although I don't understand why):
$integer = 4;
if( preg_match( '/^([0-9]+,){0,' . strval($integer) . '}[0-9]+$/', $string ) ) { ... }
Whenever concatenating a variable into a regex pattern, you should do so by passing the variable to the preg_quote function.
However, if the variable var is, like it is in your example 4, that won't make any difference. The pattern you're using will be:
/^([0-9]+,){0,4}[0-9]+$/
In which case, if it doesn't work: check the $string value, and make sure the pattern matches. BTW, /^(\d+,){,4}\d+$/ is shorter and does the same thing.
Calling strval doesn't solve anything, AFAIK... I've tested the code without strval, using the following snippet:
$string = '1234,32';
if (preg_match( '/^([0-9]+,){0,4}[0-9]+$/', $string) )
{
echo 'matches',PHP_EOL;
$count = 4;
if (preg_match( '/^([0-9]+,){0,'.$count.'}[0-9]+$/', $string ) )
echo 'matches, too',PHP_EOL;
}
The output was, as I expected:
matches
matches, too
In your case, I'd simply write:
$count = 4;
preg_match('/^(\d+,){,'.preg_quote($count, '/').'}\d+$/', $string);
This is undeniably safer than just calling strval, because you're not accounting for possible special regex chars (+[]{}/\$^?!:<=*. and the like)

PHP SEO Functions

I am having a problem trying to understand functions with variables. Here is my code. I am trying to create friendly urls for a site that reports scams. I created a DB full of bad words to remove from the url if it is preset. If the name in the url contains a link I would like it to look like this: example.com-scam.php or html (whichever is better). However, right now it strips the (.) and it looks like this examplecom. How can I fix this to leave the (.) and add a -scam.php or -scam.html to the end?
functions/seourls.php
/* takes the input, scrubs bad characters */
function generate_seo_link($link, $replace = '-', $remove_words = true, $words_array = array()) {
//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
$return = trim(ereg_replace(' +', ' ', preg_replace('/[^a-zA-Z0-9\s]/', '', strtolower($link))));
//remove words, if not helpful to seo
//i like my defaults list in remove_words(), so I wont pass that array
if($remove_words) { $return = remove_words($return, $replace, $words_array); }
//convert the spaces to whatever the user wants
//usually a dash or underscore..
//...then return the value.
return str_replace(' ', $replace, $return);
}
/* takes an input, scrubs unnecessary words */
function remove_words($link,$replace,$words_array = array(),$unique_words = true)
{
//separate all words based on spaces
$input_array = explode(' ',$link);
//create the return array
$return = array();
//loops through words, remove bad words, keep good ones
foreach($input_array as $word)
{
//if it's a word we should add...
if(!in_array($word,$words_array) && ($unique_words ? !in_array($word,$return) : true))
{
$return[] = $word;
}
}
//return good words separated by dashes
return implode($replace,$return);
}
This is my test.php file:
require_once "dbConnection.php";
$query = "select * from bad_words";
$result = mysql_query($query);
while ($record = mysql_fetch_assoc($result))
{
$words_array[] = $record['word'];
}
$sql = "SELECT * FROM reported_scams WHERE id=".$_GET['id'];
$rs_result = mysql_query($sql);
while ($row = mysql_fetch_array($rs_result)) {
$link = $row['business'];
}
require_once "functions/seourls.php";
echo generate_seo_link($link, '-', true, $words_array);
Any help understanding this would be greatly appreciated :) Also, why am I having to echo the function?
Your first real line of code has the comment:
//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
Periods are punctuation, so they're being removed. Add . to the accepted character set if you want to make an exception.
Alter your regular expression (second line) to allow full stops:
$return = trim(ereg_replace(' +', ' ', preg_replace('/[^a-zA-Z0-9\.\s]/', '', strtolower($link))));
The reason your code needs to be echoed is because you are returning a variable in the function. You can change return in the function to echo/print if you want to print it out as soon as you call the function.

php - Replacing content inside double quotes, including double quotes

So I decided to have a stab at making a text highlighting system. At the moment, I'm just using str_replace to replace a word (e.g. $rstr = str_replace("Console", "<c>Console</c>", $str where $str is the input string.
Something that stumped me was how to replace content inside of speech marks (") and quotes ('). For example, if the string "Console" turned into Console.WriteLine("Words");, how would I replace "Words" with <sr>"Words"</sr> (<sr> is defined in an external stylesheet)?
I had a though that I could use regex, but 1. I don't know how to write regex, and 2. I don't know how to use regex with str_replace.
My workaround solution:
function hlStr($original)
{
$rstr = explode('"', $original);
return $rstr[0].'<sr>"'.$rstr[1].'"</sr>'.$rstr[2];
}
In light of comments below, I think this will be a better resource for you: http://www.regular-expressions.info/
In order to find "anything can go here" you should use regular expressions. This is what they were made for. A regular expression for that might look something like the answers in this question:
How can I match a quote-delimited string with a regex?
then you would use the function preg_replace() like this:
$return_value = preg_replace('/"[^"]+"/', 'replacement text', $str)
leaving this here anyway:
just escape the content with a backslash:
$rstr = str_replace("Console", "Console.WriteLine(\"$variable\");", $str)
this is mostly useful if you are using variables inside your strings. If it is just a straight text replacement, use single quotes:
$rstr = str_replace("Console", 'Console.WriteLine("Words");', $str)
the single quotes count everything but single quotes as just a character.
This is my solution. Explode the whole string by ( " ) symbols, and then run a specific code to each second of them. This code does automatic do it to every second value after " item, which means, if you does : hej " lol ; it would change to : hi <sr>" lol "</sr> ; or if you do : hi " with " you ; it would change to : hi <sr>" with "</sr> you ; etc.
function wrapInside($text,$symbol)
{
$string = explode($symbol, $text);
$i = 1;
$QS = '';
foreach( $queryString as $V )
{
( $i == 1 ) ? ( $QS .= $V ) : ( $QS .= '<sr>"'.trim($V).'"</sr>' );
( $i == 1 ) ? ( $i = 0 ) : ( $i = 1 );
}
$queryString = trim($QS);
return $queryString;
}

Removing nested bbcode (quotes) in PHP [duplicate]

This question already has answers here:
Remove nested quotes
(3 answers)
Closed 2 years ago.
I'm trying to remove nested quoting from my bulletin board, but I'm having some issues.
Example input:
[quote author=personX link=topic=12.msg1910#msg1910 date=1282745641]
[quote author=PersonY link=topic=12.msg1795#msg1795 date=1282727068]
The message in the original quote
[/quote]
A second message quoting the first one
[/quote]
[quote author=PersonZ link=topic=1.msg1#msg1 date=1282533805]
A random third quote
[/quote]
Example output
[quote author=personX link=topic=12.msg1910#msg1910 date=1282745641]
Message in the second quote
[/quote]
[quote author=PersonZ link=topic=1.msg1#msg1 date=1282533805]
A random third quote
[/quote]
As you can see the nested quote (The original message) is removed, along with the quote tags.
I can't seem to figure it out.
When i try
$toRemove = '(\\[)(quote)(.*?)(\\])';
$string = $txt;
$found = 0; echo preg_replace("/($toRemove)/e", '$found++ ? \'\' : \'$1\'', $string);
It removes every occurrence of of the quote tag except the first one,
But when i expand the code to:
$toRemove = '(\\[)(quote)(.*?)(\\])(.*?)(\\[\\/quote\\])';
$string = $txt;
$found = 0; echo preg_replace("/($toRemove)/e", '$found++ ? \'\' : \'$1\'', $string);
It stops doing anything at all.
Any ideas on this ?
Edit:
Thanks for your help, Haggi.
Ik keep running in to trouble though.
The while loop around
while ( $input = preg_replace_callback( '~\[quoute.*?\[/quote\]~i', 'replace_callback', $input ) ) {
// replace every occurence
}
causes the page to loop indefinitely, when removed (along with the extra u in quoute), the page doesn't do anything.
I've determined that the cause is the matching
when changed to
$input = preg_replace_callback( '/\[quote(.*?)/i', 'replace_callback', $input );
the code does start working, but when changed to
$input = preg_replace_callback( '/\[quote(.*?)\[\/quote\]/i', 'replace_callback', $input );
It stopts doing anything again.
Also, there is an issue with the undo_replace function as it never finds the stored hash, it only gives warnings about unfound indexes. The regex matching the sha1 isn't working correctly i guess.
The complete code as I have it now:
$cache = array();
$input = $txt;
function replace_callback( $matches ) {
global $cache;
$hash = sha1( $matches[0] );
$cache["hash"] = $matches[0];
return "REPLACE:$hash";
}
// replace all quotes with placeholders
$input = preg_replace_callback( '/\[quote(.*?)\[quote\]/i', 'replace_callback', $input );
function undo_replace( $matches ) {
global $cache;
return $cache[$matches[1]];
}
// restore the outer most quotes
$input = preg_replace_callback( '~REPLACE:[a-f0-9]{40}~i', 'undo_replace', $input );
// remove the references to the inner quotes
$input = preg_replace( '~REPLACE:[a-f0-9]{40}~i', '', $input );
echo $input;
Thanks again for any ideas guys :)
that the first one is the only one that stays is quite easily found out:
'$found++ ? \'\' : \'$1\''
When starting $found is undefined and evaluates to false so the $1 is returned. Then $found gets incremented to 1 ( undefined + 1 = 1 ) so it is greater that zero and every time it gets called it's further incremented. As everything that is different from zero is evaluated as true after that you always get the '' back.
What you want to do is something like this
$cache = array();
function replace_callback( $matches ) {
global $cache;
$hash = sha1sum( $matches[0] );
$cache[$hash] = $matches[0];
return "REPLACE:$hash";
}
// replace all quotes with placeholders
$count = 0;
do {
$input = preg_replace_callback( '~\[quoute.*?\[/quote\]~i', 'replace_callback', $input, -1, $count );
// replace every occurence
} while ($count > 0);
function undo_replace( $matches ) {
global $cache;
return $cache[$matches[1]];
}
// restore the outer most quotes
$input = preg_replace_callback( '~REPLACE:[a-f0-9]{40}~i', 'undo_replace', $input );
// remove the references to the inner quotes
$input = preg_replace( '~REPLACE:[a-f0-9]{40}~i', '', $input );
This code is untested as I don't habe PHP at hand to test it. If there are any errors you cannot fix, please just post them here and I will fix them.
Cheers,haggi
I've searched for couple of solutions with preg_replace for nested quotes but no one worked. So i tried my littel version according to my requirement.
$position = strrpos($string, '[/quote:'); // this will get the position of last quote
$text = substr(strip_tags($string),$position+17); // this will get the data after the last quote used.
Hope this will help someone.

Categories