I have this string:
$str = 'Small ship in the sea';
I'd like to have this output:
"Small ship in the sea"
How can I accomplish this in PHP?
Thanks in advance
EDIT: The answers provided are pretty obvious. I wanted to provide a simple example, what I'm actually doing is loading a huge text file and each line is stored in multiple arrays. So each array should have the quotes at the end and at the beginning, so what would be a solution to the example provided before? Maybe using regex to add the quotes?
EDIT 2:
Apologies for the confusion this is my code:
$users = file('xls/try_traffic.txt'); //Load File
$users = preg_replace('/, TG=\d{3}/', '', $users);
$users = str_replace("LABEL=", "", $users);
$users = str_replace('"', "", $users);
$users = preg_replace("/\t/", '","', $users);
print_r($users);
I get this output (the simple version):
Array ( [0] => 01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXCABINLC
[1] => 01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZOGMV
[2] => 01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZ2WLD1
)
So I want to add the quotes at the beginning and end of each, so it looks like this:
Array ( [0] => "01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXCABINLC"
[1] => "01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZOGMV"
[2] => "01/16/2014 00:00:00","30","TLAGMSC1-MSX","TMXLPZ2WLD1"
)
Why not just make use of the concatenation . operator ?
<?php
$str = 'Small ship in the sea';
echo '"'.$str.'"'; //"prints" "Small ship in the sea"
The answers provided are pretty obvious. I wanted to put a simple
example, what I'm actually doing is loading a huge text file and each
line is stored in multiple arrays. So each array should have the
quotes at the end and at the beginning.
The code
<?php
$arr = file('yourtextfile.txt');
$new_arr = array_map('addquote',$arr);
function addquote($v)
{
return '"'.$v.'"';
}
print_r($new_arr);
I think this is what you want: EDIT 5
foreach ($users as $k => $v) {
$users[$k] = (substr($v, 0, 1) == '"') ? ($v) : ('"'. $v);
$users[$k] = (substr($v, strlen($v) -1) == '"') ? ($v) : ($v .'"');
}
print_r($users);
Check out PHP String Documentation for more details on how to deal with strings in PHP.
Personally, I use single quotes all the time, and only when absolutely necessary do I use doublequotes. It's much easier to predict string behavior with that approach IMO. Hope this helps!
Related
Using preg_match_all I retrieve (as an example) the follow string:
ABC033-101-143-147-175-142115-
Here is the code for that:
if (preg_match_all('#([A-Z]{2}C)((?:[0-9]{3}-){1,10})([0-9]{6})#', $wwalist, $matches))
I am able to get the output I want (033-101-143-147-175-) by using the following code:
$wwaInfo['locationabbrev'][$wwanum] = $matches[2][$keys[$wwanum]];
echo "locationabbrev";
From here, I need to convert the sets of 3 numbers. Every number has a corresponding abbreviation. For example, 033 = FY, 101 = CY, etc. I need locationabbrev to output a string like: "FY-CY-AY-GG-CA" as opposed to the numbers. Any idea how I would go about this?
Thanks for taking a look!
You can use strtr() with array of replacements. For example:
$locationabbrev = '033-101-143-147-175-'; // example data
// array of replacements
$replacements = [
'033' => 'FY',
'101' => 'CY',
// and so on
];
$translatedabbrev = strtr($locationabbrev, $replacements);
echo $translatedabbrev; // your final string
One method that uses explode and foreach.
Again, Tajgeers answer is very good. So unless you have some specific reason choose that.
This is just one more way to do it.
$repl = [
'033' => 'FY',
'101' => 'CY',
'143' => 'AY',
'147' => 'GG',
'175' => 'CA' ];
$locationabbrev = '033-101-143-147-175';
$arr = explode("-", $locationabbrev);
Foreach($arr as &$val){
$val= $repl[$val];
}
$result = implode("-", $arr);
Echo $result;
https://3v4l.org/iolal
Now that I think of it. If you change the regex slightly, you can get the output of the regex as my $arr. Meaning already exploded.
Still the other answer is better. Just a thought.
I want to split a string such as the following (by a divider like '~##' (and only that)):
to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date
into an array containing e.g.:
to => enquiry#test.com
subject => test
text => this is body/text
date => date
I'm using php5 and I've got the following regex, which almost works, but there are a couple of errors and there must be a way to do it in one go:
//Split the string in the url of $text at every ~##
$regexp = "/(?:|(?<=~##))(.*?=.*?)(?:~##|$|\/(?!.*~##))/";
preg_match_all($regexp, $text, $a);
//$a[1] is an array containing var1=content1 var2=content2 etc;
//Now create an array in the form [var1] = content, [var2] = content2
foreach($a[1] as $key => $value) {
//Get the two groups either side of the equals sign
$regexp = "/([^\/~##,= ]+)=([^~##,= ]+)/";
preg_match_all($regexp, $value, $r);
//Assign to array key = value
$val[$r[1][0]] = $r[2][0]; //e.g. $val['subject'] = 'hi'
}
print_r($val);
My queries are that:
It doesn't seem to capture more than 3 different sets of parameters
It is breaking on the # symbol and so not capturing email addresses e.g. returning:
to => enquiry
subject => test
text => this is body/text
I am doing multiple different regex searches where I suspect I would be able to do one.
Any help would be really appreciated.
Thanks
Why are you using regex when there is much simple method to do this by explode like this
$str = 'to=enquiry#test.com~##subject=test~##text=this is body/text~##date=date';
$array = explode('~##',$str);
$finalArr = array();
foreach($array as $val)
{
$tmp = explode('=',$val);
$finalArr[$tmp['0']] = $tmp['1'];
}
echo '<pre>';
print_r($finalArr);
I've got an array;
Array
(
[0] => Test1
[1] => Test2
[2] => Test3
)
Now I've used the Implode Function from which i got the comma separated String:
Test1, Test2, Test3
now I'd like to put a quotes ("") before and after every word e.g.
"Test1", "Test2", "Test3"
How could I change it to work how I want.
Try this simple one-liner:
$quotedStrings = '"' . implode('","', $myArray) . '"';
The "glue" parameter may be a complex string, though you only have to put the " at the beginning and end.
While the answer from Axel is totally fine for the given szenario,
using array_map along with implode will also work.
And this has the advantage, that modifications to each element are not limited to the start/end of the element. For instance, you can turn each entry to lower-case as well, or perform other, more complex operations, before applying implode.
$quotedString = implode(",", array_map("myCallback", $myArray));
function myCallback($entry){
//here you can to whatever you like to EACH element.
return '"'.$entry.'"';
}
Consider this an option
You can use make a new array by using foreach loop and then use implode. Use the code below
<?php
$array = array("Test1","Test2","Test3");
$quotes = array();
foreach($array as $p){
$quotes[] = '"'.$p.'"';
}
echo implode(",",$quotes); // Outputs "Test1","Test2","Test3"
?>
Another way you can do it by enclosing the implode in "" quotes and then implode comma , in quotes.
<?php
$array = array("Test1","Test2","Test3");
echo '"'.implode('","',$array).'"'; // Outputs "Test1","Test2","Test3"
?>
Hope this helps you
How do I modify the last element in an array?
The array looks like this:
$fields = array("firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', ");
The array is generated by a script which creates the values and adds the comma/space at the end of each string. I want to remove that comma/space from only the last element in that array. Keep in mind that the values could in fact contain a comma/space combination so only the last element and the last two characters of the last element need to be removed.
I've looked at the end() function but I don't think that is going to help since it just gets the value.
Edit Ok so I created this function/array so that I would only have one mysql function to update users. Sort of like a detect changes function and it only passes back the required/changed fields. I didn't realize there were problems associated with this approach. I thought that since I already had the mysql queries written in my old functions there shouldn't be an issue with this way. The file that it's in will not be accessible to the public. I'm going to use the best answer that works for me but I'm going to search for why this is problematic and I would appreciate comments/links as to what is wrong with this approach.
Like this!
end($array);
$key = key($array);
reset($array);
There's a shorthand way to do this, but it's easier to follow if it's broken out into pieces:
$index = count( $fields ) - 1;
$value = $fields[$index];
$fields[$index] = preg_replace( "/,\ $/", "", $value );
To change the value of the last numeric element:
$lastValue = array_pop($fields);
$fields[] = rtrim(', ',$lastValue);
If you are preparing these values for a query I would suggest storing everything without commas in an array then calling implode on that array when needed to prevent trailing comma problems
Array pop and push are the easiest way to do it for basic arrays. (I know that isn't technically the question but many people will come here looking for the answer in relation to simple arrays as well).
<?php
function update_last(&$array, $value){
array_pop($array);
array_push($array, $value);
}
?>
Then you can use the function like this:
<?php
$array = [1,2,3];
update_last($array, 4); //$array = [1,2,4];
?>
There are few ways:
1) For associative arrays, if you don't know the last element key, you better find the last element key first and change its value.
$array[end((array_keys($array)))] .= ' additional text';
2) if you don't know and don't care about keys, you can cut the last element and create a new one.
$array[] = array_pop($array).' additional text';
The last element of an array can always be retrieved using array_pop(), no matter how the array is indexed. It will also remove that element from the array, which is very useful if we want to modify and then add it again, as you cannot modify the element in-place.
What you are trying to do can be done with a simple, single line of code:
$fields[] = preg_replace("/, $/", "", array_pop($fields));
That's it. Here's what it does:
preg_replace() searches for a Regex pattern in a string and if found, replaces the match with an alternative string.
The pattern we search for is /, $/, which means: Match for ", " (comma + space) but only if it is at the very end of the string ($).
The replacement string is simply an empty string (""), thus the match is just deleted from the string.
The string we want to perform that replacement on is array_pop($fields), the last element of the array $fields, which is also removed from that array.
The modified string is then re-added to the array at the end ($fields[] = adds an element to an array without an explicit key and makes it the new last element).
Let's test it:
$fields = array(
"firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', ");
print "Before:\n\n";
print_r($fields);
$fields[] = preg_replace("/, $/", "", array_pop($fields));
print "\nAfter:\n\n";
print_r($fields);
Output:
Before:
Array
(
[0] => firstName = 'Bob',
[1] => lastName = 'Smith',
[2] => email = 'bob#example.com',
[3] => address = '123 anystreet',
)
After:
Array
(
[0] => firstName = 'Bob',
[1] => lastName = 'Smith',
[2] => email = 'bob#example.com',
[3] => address = '123 anystreet'
)
Note how the last comma is gone? Just try it yourself.
stumbled upon this today. i think the easiest non-pointer-breaking way would be:
array_splice($array, -1, 1, strtolower(end(array_values($array))).'blah' );
of course you can drop array_values if you dont have to care for the pointer.
but i wonder if this is a good way, since the extract-n-replace-stuff of splice could be more demanding than a pop or sth?
PHP 7 >= 7.3.0
$array[array_key_last($array)] = 'new value';
Demo
$fields = array(
"firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', "
);
$last = $fields[array_key_last($fields)];
$last = preg_replace( "/, $/", "", $last);
$fields[array_key_last($fields)] = $last;
I think PHP's Implode function might be a good alternative, instead of generating the commas yourself.
Barring that, you would have to use something like:
$lastfield = $fields[count($fields)-1];
$lastfield = str_split($lastfield,strlen($lastfield)-2);
$fields[count($fields)-1] = $lastfield;
The first and third lines are included to make the second line easier to read, but this could easily be compounded to one line.
I have a string
&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&
and i have to delete, say, this part &185601651932|mobile|3|120|1& (starting with amp and ending with amp) knowing only the first number up to vertical line (185601651932)
so that in result i would have
&168491968426|mobile|3|100|1&114192088691|mobile|3|555|5&
How could i do that with PHP preg_replace function. The number of line (|) separated values would be always the same, but still, id like to have a flexible pattern, not depending on the number of lines in between the & sign.
Thanks.
P.S. Also, I would be greatful for a link to a good simply written resource relating regular expressions in php. There are plenty of them in google :) but maybe you happen to have a really great link
preg_replace("/&185601651932\\|[^&]+&/", ...)
Generalized,
$i = 185601651932;
preg_replace("/&$i\\|[^&]+&/", ...);
if you want real flexibility, use preg_replace_callback. http://php.net/manual/en/function.preg-replace-callback.php
Important: don't forget to escape your number using preg_quote():
$string = '&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$number = 185601651932;
if (preg_match('/&' . preg_quote($number, '/') . '.*?&/', $string, $matches)) {
// $matches[0] contains the captured string
}
It seems to me you ought to be using another data structure than a string to manipulate this data.
I'd want this data in a structure like
Array(
[id] => Array(
[field_1] => value_1
[field_2] => value_2
)
)
Your massive string can be massaged into such a structure by doing something like this:
$data_str = '168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
$remove_num = '185601651932';
/* Enter a descriptive name for each of the numbers here
- these will be field names in the data structure */
$field_names = array(
'number',
'phone_type',
'some_num1',
'some_num2',
'some_num3'
);
/* split the string into its parts, and place them into the $data array */
$data = array();
$tmp = explode('&', trim($data_str, '&'));
foreach($tmp as $record) {
$fields = explode('|', trim($record, '|'));
$data[$fields[0]] = array_combine($field_names, $fields);
}
echo "<h2>Data structure:</h2><pre>"; print_r($data); echo "</pre>\n";
/* Now to remove our number */
unset($data[$remove_num]);
echo "<h2>Data after removal:</h2><pre>"; print_r($data); echo "</pre>\n";