So a simple example would be
$ar = array("some text","more text","yet more text");
foreach($ar as $value){
echo $value."<br>";
}
I get the result
some text
more text
yet more text
so my question is when we do this inside foreach loop "$ar as $value",
I know that $ar is array but what about second one the $value is it simple
variable or is it yet another array? Because we can do it in the following way too
foreach($ar as $value){
echo $value[0]."<br>";
}
Which would result in
s
In PHP, strings are byte arrays. Referencing position 0 of $value refers to the position (0) in the string (s in some test)
Your actual array looks like this:
Array
(
[0] => some text
[1] => more text
[2] => yet more text
)
If you want to access the index position of the array you can do:
foreach($ar as $key=>$val) {
echo "$key - $val";
}
Which will output:
0 - some text
1 - more text
2 - yet more text
$value is a value in array and is not an array itself unless you have nested arrays (array(array('a','b'),array('b','c'))). Subscripting strings, though, is still possible and this is how your got the first character of the string.
You should get
s m y
on separate lines.
BTW the br tag is old hat.
The thing is that doing $value[0] access the first character of the string.
A string is internally represented as an array. So accessing to the index 0 of a string is like accessing to the first character.
That is why it prints "s" because your string "some text" starts with s
You can see your example as the following
array(
[0] => array(
[0] => 's',
[1] => 'o',
[2] => 'm',
[3] => 'e',
//...
),
[1] => array(
[0] => 'm',
[1] => 'o',
[2] => 'r',
[3] => 'e',
//...
),
//...
);
String access and modification by character is possible in PHP. What you need to know, and probably didn't know is that while strings are expresses as string, sometimes they can be considered as arrays: let's look at this example:
$text = "The quick brown fox...";
Now, if you were to echo $text[0] you would get the first letter in the string which in this case happens to be T, or if you wanted to modify it, doing $text[0] = "A"; then you will be changing the letter "T" to "A"
Here is a good tutorial from the PHP Manual, It shows you how strings can be accessed/modified by treating them as an array.
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
// Get the third character of a string
$third = $str[2];
// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';
?>
BTW: If you had only wanted to display, the first value inside your array, you could use something like
<?php
$ar = array("some text","more text","yet more text");
for ($i=1; $i<=1; $i++)
{
echo $ar[0];
}
?>
Related
This question already has answers here:
php explode all characters [duplicate]
(4 answers)
Closed 8 years ago.
how i can explode string into an array. Acctually i want to translate english language into the braille. First thing i need to do is to get the character one by one from a string,then convert them by mathing the char from value in database and display the braille code using the pic. As example when user enter "abc ef", this will create value separately between each other.
Array
(
[0] => a
[1] => b
[2] => c
[3] =>
[4] => e
[5] => f
)
i tried to do but not get the desired output. This code separated entire string.
$papar = preg_split('/[\s]+/', $data);
print_r($papar);
I'm sorry for simple question,and if you all have an idea how i should do to translate it, feel free to help. :)
If you're using PHP5, str_split will do precisely what you're seeking to accomplish. It splits each character in a string – including spaces – into an individual element, then returns an array of those elements:
$array = str_split("abc ef");
print_r($array);
Outputs the following:
Array
(
[0] => a
[1] => b
[2] => c
[3] =>
[4] => e
[5] => f
)
UPDATE:
The PHP4 solution is to use preg_split. Pass a double forward slash as the matching pattern to delimit the split character-by-character. Then, set the PREG_SPLIT_NO_EMPTY flag to ensure that no empty pieces will be returned at the start and end of the string:
$array = preg_split('//', "abc ef", -1, PREG_SPLIT_NO_EMPTY); // Returns same array as above
PHP has a very simple method of getting the character at a specific index.
To do this, utilize the substring method and pass in the index you are looking for.
How I would approach your problem is
Ensure the string you are converting has at least a size of one
Determine how long the string is
int strlen ( string $string )
Loop over each character and do some operation depending on that character
With a string "abcdef"
$rest = substr("abcdef", -1); // returns "f"
See the substr page for a full example and more information
http://us2.php.net/substr
You can iterate the string itself.
$data = 'something string';
for($ctr = 0; $ctr < strlen($data); $ctr++)
{
if($data{$ctr}):
$kk = mysql_query("select braille_teks from braille where id_huruf = '$data{$ctr}'");
$jj = mysql_fetch_array($kk);
$gambar = $jj['braille_teks'];
?>
<img src="images/<?php echo $gambar;?>">
<?php
else:
echo " ";
}
I want to split a string from behind. Like:
$mystring = "this is my string";
$mysecondstring = "thisismystring";
I want to split the last 6 characters from the above strings, here it is "string". How can I do this in PHP?
Using str_split, I can split from the front side, but I need from the end.
Thanks in advance.
Use substr()
edit
$snippet = substr($mystring, 0, -6);
Was looking for something like it too, (almost 10 years later ..)
Here it's what i've made :
function str_split_end($string, $length) {
$string = strrev($string);
$array = str_split($string, $length);
$array = array_reverse($array);
for($i = 0; $i < sizeof($array); $i++) {
$array[$i] = strrev($array[$i]);
}
return $array;
}
In your case, the function will return with $mystring :
array (
0 => 'this ',
1 => 'is my ',
2 => 'string',
)
And with $mysecondstring :
array (
0 => 'th',
1 => 'isismy',
2 => 'string',
)
Using str_split() will Convert a string to an array
But can get the same result output you want in an array form
// The first parameter would the string you want to split.
// then the second parameter would be in what length you want the string to be splitted.
str_split(parameter1,parameter2)
Example.
$mystring = " this is my string ";
// we put length of string to be splitted by 6 because its the string length of "string"
$myString = str_split($myString,6);
It will generate a result of :
Output:
Array
(
[0] => " this "
[1] => "is my "
[2] => "string"
// then you can
echo $string[2]
//for the value of "string" being splitted.
)
note: if your using str_split() to get a value you want you must have a good division length for it. That why i add extra spaces in the value of $mystring to only produce an output array of "string" as value
This code will split the string into an array that contains test and string:
$str = 'test string';
$arr = preg_split('/\s+/', $str);
But I also want to detect quotes and ignore the text between them when splitting, for example:
$str = 'test "Two words"';
This should also return an array with two elements, test and Two words.
And another form, if possible:
$str = 'test=Two Words';
So if the equal sign is present before any spaces, the string should be split by =, otherwise the other rules from above should apply.
So how can I do this with preg_split?
Try str_getcsv:
print_r(str_getcsv('test string'," "));
print_r(str_getcsv('test "Two words"'," "));
print_r(str_getcsv('test=Two Words',"="));
Outputs
Array
(
[0] => test
[1] => string
)
Array
(
[0] => test
[1] => Two words
)
Array
(
[0] => test
[1] => Two Words
)
You can use something like preg_match to check if there's an equal sign exist before space and then determine what delimiter to use.
Works only in PHP>=5.3 though.
I'm sure this could be done with regex, but how about just splitting the string by quotation marks, then by spaces, using explode?
Given the string 'I am a string "with an embedded" string', you could first split by quotation marks, giving you ['I am a string', 'with an embedded', 'string'], then you go over every other element in the array and split by spaces, resulting in ['I', 'am', 'a', 'string', 'with an embedded', 'string'].
The exact code to do this you can probably write yourself. If not, let me know and I'll help you.
In your last example, just split by the equals symbol:
$str = 'test=Two Words';
print explode('=', $str);
I'd like to parse a string like the following :
'serviceHits."test_server"."http_test.org" 31987'
into an array like :
[0] => serviceHits
[1] => test_server
[2] => http_test.org
[3] => 31987
Basically I want to split in dots and spaces, treating strings within quotes as a single value.
The format of this string is not fixed, this is just one example. It might contain different numbers of elements with quoted and numerical elements in different places.
Other strings might look like :
test.2 3 which should parse to [test|2|3]
test."342".cake.2 "cheese" which should parse to [test|342|cake|2|cheese]
test."red feet".3."green" 4 which should parse to [test|red feet|3|green|4]
And sometimes the oid string may contain a quote mark, which should be included if possible, but it's the least important part of the parser:
test."a \"b\" c" "cheese face" which should parse to [test|a "b" c|cheese face]
I'm trying to parse SNMP OID strings from agent written by people with quite varying ideas on what an OID should look like, in a generic manner.
Parsing off the oid string (the bit separated with dots) return value (the last value) into separate named arrays would be nice. Simply splitting on space before parsing the string wouldn't work, as both the OID and the value can contain spaces.
Thanks!
I agree this can be hard to find one regexp to resolve this issue.
Here's a complete solution :
$results = array();
$str = 'serviceHits."test_\"server"."http_test.org" 31987';
// Encode \" to something else temporary
$str_encoded_quotes = strtr($str,array('\\"'=>'####'));
// Split by strings between double-quotes
$str_arr = preg_split('/("[^"]*")/',$str_encoded_quotes,-1,PREG_SPLIT_DELIM_CAPTURE);
foreach ($str_arr as $substr) {
// If value is a dot or a space, do nothing
if (!preg_match('/^[\s\.]$/',$substr)) {
// If value is between double-quotes, it's a string
// Return as is
if (preg_match('/^"(.*)"$/',$substr)) {
$substr = preg_replace('/^"(.*)"$/','\1',$substr); // Remove double-quotes around
$results[] = strtr($substr,array('####'=>'"')); // Get escaped double-quotes back inside the string
// Else, it must be splitted
} else {
// Split by dot or space
$substr_arr = preg_split('/[\.\s]/',$substr,-1,PREG_SPLIT_NO_EMPTY);
foreach ($substr_arr as $subsubstr)
$results[] = strtr($subsubstr,array('####'=>'"')); // Get escaped double-quotes back inside string
}
}
// Else, it's an empty substring
}
var_dump($results);
Tested with all of your new string examples.
First attempt (OLD)
Using preg_split :
$str = 'serviceHits."test_server"."http_test.org" 31987';
// -1 : no limit
// PREG_SPLIT_NO_EMPTY : do not return empty results
preg_split('/[\.\s]?"[\.\s]?/',$str,-1,PREG_SPLIT_NO_EMPTY);
The easiest way is probably to replace dots and spaces inside strings with placeholders, split, then remove the placeholders. Something like this:
$in = 'serviceHits."test_server"."http_test.org" 31987';
$a = preg_replace_callback('!"([^"]*)"!', 'quote', $in);
$b = preg_split('![. ]!', $a);
foreach ($b as $k => $v) $b[$k] = unquote($v);
print_r($b);
# the functions that do the (un)quoting
function quote($m){
return str_replace(array('.',' '),
array('PLACEHOLDER-DOT', 'PLACEHOLDER-SPACE'), $m[1]);
}
function unquote($str){
return str_replace(array('PLACEHOLDER-DOT', 'PLACEHOLDER-SPACE'),
array('.',' '), $str);
}
Here is a solution that works with all of your test samples (plus one of my own) and allows you to escape quotes, dots, and spaces.
Due to the requirement of handling escape codes, a split is not really possible.
Although one can imagine a regex that matches the entire string with '()' to mark the separate elements, I was unable to get it working using preg_match or preg_match_all.
Instead I parsed the string incrementally, pulling off one element at a time. I then use stripslashes to unescape quotes, spaces, and dots.
<?php
$strings = array
(
'serviceHits."test_server"."http_test.org" 31987',
'test.2 3',
'test."342".cake.2 "cheese"',
'test."red feet".3."green" 4',
'test."a \\"b\\" c" "cheese face"',
'test\\.one."test\\"two".test\\ three',
);
foreach ($strings as $string)
{
print"'{$string}' => " . print_r(parse_oid($string), true) . "\n";
}
/**
* parse_oid parses and OID and returns an array of the parsed elements.
* This is an all-or-none function, and will return NULL if it cannot completely
* parse the string.
* #param string $string The OID to parse.
* #return array|NULL A list of OID elements, or null if error parsing.
*/
function parse_oid($string)
{
$result = array();
while (true)
{
$matches = array();
$match_count = preg_match('/^(?:((?:[^\\\\\\. "]|(?:\\\\.))+)|(?:"((?:[^\\\\"]|(?:\\\\.))+)"))((?:[\\. ])|$)/', $string, $matches);
if (null !== $match_count && $match_count > 0)
{
// [1] = unquoted, [2] = quoted
$value = strlen($matches[1]) > 0 ? $matches[1] : $matches[2];
$result[] = stripslashes($value);
// Are we expecting any more parts?
if (strlen($matches[3]) > 0)
{
// I do this (vs keeping track of offset) to use ^ in regex
$string = substr($string, strlen($matches[0]));
}
else
{
return $result;
}
}
else
{
// All or nothing
return null;
}
} // while
}
This generates the following output:
'serviceHits."test_server"."http_test.org" 31987' => Array
(
[0] => serviceHits
[1] => test_server
[2] => http_test.org
[3] => 31987
)
'test.2 3' => Array
(
[0] => test
[1] => 2
[2] => 3
)
'test."342".cake.2 "cheese"' => Array
(
[0] => test
[1] => 342
[2] => cake
[3] => 2
[4] => cheese
)
'test."red feet".3."green" 4' => Array
(
[0] => test
[1] => red feet
[2] => 3
[3] => green
[4] => 4
)
'test."a \"b\" c" "cheese face"' => Array
(
[0] => test
[1] => a "b" c
[2] => cheese face
)
'test\.one."test\"two".test\ three' => Array
(
[0] => test.one
[1] => test"two
[2] => test three
)
<a href="http://www.google.com/search?q='.urlencode(current(explode('(', $ask_key))).'" target="_blank">
I can't understand what urlencode(current(explode('(', $ask_key ))) does.
Can anybody explain me what that code does?
explode the string $ask_key into an array using ( as the delimiter (so if the value of $ask_key is a(b(c, then array('a', 'b', 'c') will be returned.
and grab the first, i.e., current (as a new array will be pointing to its first element), element of that array
then urlencode it (making it safe for use in a query string).
$array is an string, that must contain several values, separated by (.
explode() will split this string into an array, using ( as a separator.
current() will get the current element of the array -- the first one.
and, finally, urlencode() will encode special characters, so they can be used in an URL.
So, basically :
Take the first element of a string such as these(are(elements
apply the urlencode function to it, so it can be used in an URL.
As an example, here is the same kind of code, split into several distinct operations, using a variable to store the result of each function -- so we can dump those results :
$string = "th#is?i&s(a couple(of elements";
var_dump($string);
$array = explode('(', $string);
var_dump($array);
$first_item = current($array);
var_dump($first_item);
$encoded = urlencode($first_item);
var_dump($encoded);
The four var_dump() will give this output :
string 'th#is?i&s(a couple(of elements' (length=30)
array
0 => string 'th#is?i&s' (length=9)
1 => string 'a couple' (length=8)
2 => string 'of elements' (length=11)
string 'th#is?i&s' (length=9)
string 'th%40is%3Fi%26s' (length=15)
Which shows in details what each portion of your expression does.
$ask_key = 'as das df(sdfkj as(asf a152451(sdfa df1 9'; //you key
echo $ask_key."<br/>";
$array = explode('(', $ask_key); //explode will split the array on '('
echo "<pre>";
print_r($array);
echo "</pre>";
$curr = current($array); //current will return the curr element of array
echo $curr."<br/>";
$enc = urlencode($curr); //url will encode url i.e. valid url
echo $enc;
Result::
as das df(sdfkj as(asf a152451(sdfa df1 9
Array
(
[0] => as das df
[1] => sdfkj as
[2] => asf a152451
[3] => sdfa df1 9
)
as das df
as+das++df