PHP, explode multiple words and prefix them with a character [duplicate] - php

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

Related

Search and replace all lines in a multiline string

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

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

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;
}

How to print $ with php

Basically I have a block of html that I want to echo to the page and the html has the $ sign in it and the php thinks it is a variable so $1 is treated as the variable not the value and is not displayed.
There is the standard answers here but none are working: PHP: How to get $ to print using echo
My next idea is to split the string at the $ and echo each part out.
Here is the code I have tried echo and print.
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
//$s = str_replace('$', '#', $s);
$s = str_replace('$', '\$', $s);
//echo "$s" . "<br>";
print $s;
}
All help appreciated.
OK I solved by using the character code value for $
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
$s = str_replace('$', '$', $s);
echo $s . "<br>";
}
I figured I should just post it anyway.
Thanks,
Mat
Or you could echo string literal using single quotes...
<?php
echo 'Give me $1';
?>
will print:
Give me $1
PHP string docs:
http://php.net/manual/en/language.types.string.php
Side note - the link you provide has many answers that would work perfectly. How are you applying them in a way that doesn't work?
Just use a single quoted string.
$foo = 'Hello';
echo '$foo'; // $foo
echo "$foo"; // Hello
You're doing it in the wrong place. Variable interpolating is done when double quoted string literal (which in your case is stored within $rowmk->longdescription is daclared. Once it's done, you can't really do anything to get your $s back.
Solution, do proper escaping, when you declare the string.
I assume you read your rows from a database. Dollar Signs inside these strings will not be interpolated by php. Here's a little test script to try it out:
// you'd first have to set the three variables according to your database
$dbh = new PDO($DSN, $DB_USER, $DB_PASS);
// create a table and insert a string containing a dollar sign
$dbh->exec('CREATE TABLE IF NOT EXISTS some_text ( longdescription VARCHAR( 255 ))');
$dbh->exec('INSERT INTO some_text ( longdescription ) VALUES ( "10 $" )');
// query all the data from the table
$query =$dbh->query("SELECT * FROM some_text");
$rows = $query->fetchAll(PDO::FETCH_CLASS);
// loop over all the rows (as in your example) and output the rows
// no problem at all
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
echo $s . "<br>";
}
You can use "\$"
ex:
"\$stringvalue"
I did it using this
echo "$" . "VariableName";

String manipulation into two parts in PHP

Can someone suggest a simple function that will parse a string into two parts, based on everything before and after the comma? I want to split up a latitude longitude pair so that I have two variables instead of one.
I need to turn this:
-79.5310706,43.6918950
into this:
-79.531070
43.6918950
$parts = explode(",", "-79.5310706,43.6918950");
echo $parts[0];
// -79.5310706
echo $parts[1];
// 43.69189506
Or if you need it to stay as a space-separated string, just str_replace() the comma to a space!
echo str_replace(",", " ", "-79.5310706,43.6918950");
// -79.531070 43.6918950

Categories