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
Related
Currently I am trying to split the � the special character which represents %A0 at the URL. However when I use another URL, it doesn't recognize %A0 therefore I need to use %20 which is the standard space.
My question is. Is there a way to explode() special character �? Whenever I try to explode, it always return a single index array with length 1 array.
//Tried str_replace() to replace %A0 to empty string. Didn't work
$a = str_replace("%A0"," ", $_GET['view']);
// Tried to explode() but still returning single element
$b = explode("�", $a);
// Returning Array[0] => "Hello World" insteand of
// Array[2] => [0] => "Hello", [1] => "World"
echo $b[0];
Take a look at mb_split:
array mb_split ( string $pattern , string $string [, int $limit = -1 ] )
Split a multibyte string using regular expression pattern and returns
the result as an array.
Like this:
$string = "a�b�k�e";
$chunks = mb_split("�", $string);
print_r($chunks);
Outputs:
Array
(
[0] => a
[1] => b
[2] => k
[3] => e
)
I'm writing a PHP function to extract numeric ids from a string like:
$test = '123_123_Foo'
At first I took two different approaches, one with preg_match_all():
$test2 = '123_1256_Foo';
preg_match_all('/[0-9]{1,}/', $test2, $matches);
print_r($matches[0]); // Result: 'Array ( [0] => 123 [1] => 1256 )'
and other with preg_replace() and explode():
$test = preg_replace('/[^0-9_]/', '', $test);
$output = array_filter(explode('_', $test));
print_r($output); // Results: 'Array ( [0] => 123 [1] => 1256 )'
Any of them works well as long as the string does not content mixed letters and numbers like:
$test2 = '123_123_234_Foo2'
The evident result is Array ( [0] => 123 [1] => 1256 [2] => 2 )
So I wrote another regex to get rid off of mixed strings:
$test2 = preg_replace('/([a-zA-Z]{1,}[0-9]{1,}[a-zA-Z]{1,})|([0-9]{1,}[a-zA-Z]{1,}[0-9]{1,})|([a-zA-Z]{1,}[0-9]{1,})|([0-9]{1,}[a-zA-Z]{1,})|[^0-9_]/', '', $test2);
$output = array_filter(explode('_', $test2));
print_r($output); // Results: 'Array ( [0] => 123 [1] => 1256 )'
The problem is evident too, more complicated paterns like Foo2foo12foo1 would pass the filter. And here's where I got a bit stuck.
Recap:
Extract a variable ammount of chunks of numbers from string.
The string contains at least 1 number, and may contain other numbers
and letters separated by underscores.
Only numbers not preceded or followed by letters must be extracted.
Only the numbers in the first half of the string matter.
Since only the first half is needed I decided to split in the first occurrence of letter or mixed number-letter with preg_split():
$test2 = '123_123_234_1Foo2'
$output = preg_split('/([0-9]{1,}[a-zA-Z]{1,})|[^0-9_]/', $test, 2);
preg_match_all('/[0-9]{1,}/', $output[0], $matches);
print_r($matches[0]); // Results: 'Array ( [0] => 123 [1] => 123 [2] => 234 )'
The point of my question is if is there a simpler, safer or more efficient way to achieve this result.
If I understand your question correctly, you want to split an underscore-delimited string, and filter out any substrings that are not numeric. If so, this can be achieved without regex, with explode(), array_filter() and ctype_digit(); e.g:
<?php
$str = '123_123_234_1Foo2';
$digits = array_filter(explode('_', $str), function ($substr) {
return ctype_digit($substr);
});
print_r($digits);
This yields:
Array
(
[0] => 123
[1] => 123
[2] => 234
)
Note that ctype_digit():
Checks if all of the characters in the provided string are numerical.
So $digits is still an array of strings, albeit numeric.
Hope this helps :)
Getting just the numeric part of the string after the explode
$test2 = "123_123_234_1Foo2";
$digits = array_filter(explode('_', $test2 ), 'is_numeric');
var_dump($digits);
Result
array(3) { [0]=> string(3) "123" [1]=> string(3) "123" [2]=> string(3) "234" }
Use strtok
Regex isn't a magic bullet, and there are FAR simpler fixes for your problem, especially considering you're trying to split on a delimiter.
Any of the following approaches would be cleaner, and more maintainable, and the strtok() approach would probably perform better:
Use explode to create and loop through an array, checking each value.
Use preg_split to do the same, but with more a adaptable approach.
Use strtok, as it is designed exactly for this use-case.
Basic exmple for your case:
function strGetInts(string $str, str $delim) {
$word = strtok($str, $delim);
while (false !== $word) {
if (is_integer($word) {
yield (int) $word;
}
$word = strtok($delim);
}
}
$test2 = '123_1256_Foo';
foreach(strGetInts($test2, '_-') as $key {
print_r($key);
}
Note: the second argument to strtok is string containing ANY delimiter to split the string on. Thus, my example will group results into strings separated by underscores or dashes.
Additional Note: If and only if the string only needs to be split on a single delimiter (underscore only), a method using explode will likely result in better performance. For such a solution, see the other answer in this thread: https://stackoverflow.com/a/46937452/1589379 .
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];
}
?>
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