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;
}
Related
I'm trying to change straight quotes ("something") to curly quotes („something“) in PHP. Other answers are not for my situation, since I have a product details imported from DB as variable, using str_replace I've managed to only change it to „ and it seems like I can't change the second one to be “. From what I know, there is no way to accomplish this.
For example:
$description outputs -> Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.
What I would like:
$description outputs -> Hello „everyone“, I would like to „change“ this straight „quotes“ to „curly“ ones.
Try using preg_replace with the pattern "(.*?)". Then, replace with the capture group $1 inside curly quotes.
$input = "Hello \"everyone\", I would like to \"change\" this straight \"quotes\" to \"curly\" ones.";
$output = preg_replace("/\"(.*?)\"/", "„$1“", $input);
echo $output;
This prints:
Hello „everyone“, I would like to „change“ this straight „quotes“ to „curly“ ones.
Edit:
You are trying to replace HTML code, where double quotes have been encoded, so try the following:
$input = "Exklusiv von buttinette: Baumwollstoff "Leo",";
$output = preg_replace("/"(.*?)"/", "“$1”", $input);
echo $output;
This prints:
Exklusiv von buttinette: Baumwollstoff “Leo”,
Using explode and array_reduce:
$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';
$parts = explode('"', $str); // or explode('"', $str);
$carry = array_shift($parts);
$result = array_reduce($parts, function ($c,$i) {
static $up = false;
return $c . ((true === $up=!$up) ? '„' : '“') . $i;
}, $carry) ;
demo
Obviously if your original quotes are html entities you have to change the first parameter of explode.
Using strtok:
$str = 'Hello "everyone", I would like to "change" this straight "quotes" to "curly" ones.';
$result = substr(strtok(".$str", '"'), 1);
while (false !== $part = strtok('"')) {
$result .= "„${part}“" . strtok('"');
}
demo
I have a string with a large list with items named as follows:
str = "f05cmdi-test1-name1
f06dmdi-test2-name2";
So the first 4 characters are random characters. And I would like to have an output like this:
'mdi-test1-name1',
'mdi-test2-name2',
As you can see the first characters from the string needs to be replaced with a ' and every line needs to end with ',
How can I change the above string into the string below? I've tried for ours with 'strstr' and 'str_replace' but I can't get it working. It would save me a lot of time if I got it work.
Thanks for your help guys!
Here is a way to do the job:
$input = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$result = preg_replace("/.{4}(\S+)/", "'$1',", $input);
echo $result;
Where \S stands for a NON space character.
EDIT : I deleted the above since the following method is better and more reliable and can be used for any possible combination of four characters.
So what do I do if there are a million different possibillites as starting characters ?
In your specific example I see that the only space is in between the full strings (full string = "f05cmdi-test1-name1" )
So:
str = "f05cmdi-test1-name1 f06dmdi-test2-name2";
$result_array = [];
// Split at the spaces
$result = explode(" ", $str);
foreach($result as $item) {
// If four random chars take string after the first four random chars
$item = substr($item, 5);
$result_array = array_push($result_arrray, $item);
}
Resulting in:
$result_array = [
"mdi-test1-name1",
"mdi-test2-name2",
"....."
];
IF you would like a single string in the style of :
"'mdi-test1-name1','mdi-test2-name2','...'"
Then you can simply do the following:
$result_final = "'" . implode("','" , $result_array) . "'";
This is doable in a rather simple regex pattern
<?php
$str = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$str = preg_replace("~[a-z0-9]{1,4}mdi-test([0-9]+-[a-z0-9]+)~", "'mdi-test\\1',", $str);
echo $str;
Alter to your more specific needs
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.
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)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Add a prefix to each item of a PHP array
I try to use Boolean mode full text search.
If a user types more than two words, it supposes to make like this.
Search Keyword : Apple Macbook Air
Result : +Apple +Macbook +Air
So, I made a php command to make this happen, but didn't work.
$ArrayKeywords = explode(" ", $b_keyword);
for($i = 0; $i < sizeof($ArrayKeywords); $i++)
$array_keyword = '+"$ArrayKeywords[$i]" ';
can you tell me how to make this happen?
Can also do (demo)
echo preg_replace('(\w+)', '+$0', 'Apple Macbook Air');
Why not just do this:
$keyword = '+' . trim(str_replace(' ',' +',$b_keyword));
Don't really need to for loop there
// trims off consecutive spaces in the search term
$b_keyword = preg_replace('/\s+/', ' ', $b_keyword);
$ArrayKeywords = explode(" ", $b_keyword);
echo '+' . implode(' +', $ArrayKeywords);
I see there's a bit of a misunderstanding how variables inside strings work.
You may have learned that anything inside single quotes is parsed as is and inside double quotes the variables' contents are printed, like so:
$foo = 'bar';
echo 'foo: $foo'; // result: foo: $foo
echo "foo: $foo"; // result: foo: bar
But, you can't combine the two methods; putting double quotes inside single quotes doesn't make the variable's contents printed. The double quotes work only if the entire string is delimited by them. Therefore the following won't work:
echo 'foo: "$foo"'; // result: foo: "$foo"
Expanding this to your case, you can just replace the single quotes with double quotes and drop the inner double quotes.
$array_keyword .= "+$ArrayKeywords[$i] ";
Also note that you have to concatenate the new words into the variable (.=), otherwise the variable is overwritten on each loop.
Side note: it's much easier to use a foreach loop than a for loop when looping through arrays:
$ArrayKeywords = explode(" ", $b_keyword);
$array_keyword = '';
foreach( $ArrayKeywords as $keyword ) {
$array_keyword .= '+$keyword ";
}
If you want it for tabs, newlines, spaces, etc.
echo preg_replace('(\s+)', '$0+', ' Apple Macbook Air');
//output: +Apple +Macbook +Air