Removing everything after the last instance of a specific character - php

Let's say I have a string, like this:
$my_string = 'hello_world-my_name_is-holl';
My goal is to run this through a function, and end up with:
'hello_world-my_name_is'
I want to get rid of everything after the last instance of a hyphen. There can be more than two. My idea was trying something like this:
$arr = explode("-", $my_string);
$arr = array_pop($arr);
$new_name = implode('', $arr);
But that doesn't seem to work. What's a good short way of achieving what I'm looking for?

The reason why your code doesn't work is twofold:
first off, array_pop() modifies the passed array PLUS returns what it popped off. That means what you are doing here is re-assigning "holl" (a string) to your $arr variable and therefore it is no longer an array. That is why the following implode function fails. The second argument needs to be an array, not a string.
Secondly, you'll want to use the hyphen as a glue when putting the array back together into a string. So, the following should work.
$my_string = 'hello_world-my_name_is-holl';
$arr = explode("-", $my_string);
$arr2 = array_pop($arr);
$new_name = implode('-', $arr);
echo $new_name;
As you can see, I assigned the popped-off "holl" to a new variable (in case you need it), but then imploded the original, but modified array $arr.

Related

Trim string with array using PHP

How can i trim with array of string in php. If I have an dynamic array as follows :
$arr = array(' ','<?php','?>',"'",'"');
so how can i use this array in trim() to remove those string, I tried very hard in the code below :
$text = trim(trim(trim(trim(trim($text),'<?php'),'?>'),'"'),"'");
but i can not use this because array is dynamic, it may have more than 1000 values.
It takes a lot of time to turn into a loop even after trying it.So I can do anything as follows
$text = trim($text, array(' ','<?php','?>',"'",'"') );
It's possible to apply trim() function to an array. The question seems to be unclear but you can use array_map(). Unclear because there are other enough possible solutions to replace substrings. To just apply trim() function to an array, use the following code.
$array = array(); //Your array
$trimmed_array = array_map('trim', $array); //Your trimmed array is here
If you also want to fulfill the argument requirement in trim() you can apply a custom anonymous function to array_map() like this:
$array = array(); //Your array
$trimmed_array = array_map(function($item){
return trim($item, 'characters to be stripped');
}, $array); //Your trimmed array is here

how to input elements instead of another array, into end of array?

Due to bad DB design, there may be several values in a column # each row in a table. So I had to take in every string, check if commas exist (multiple values) & place each element into the end of an array.
Did try out functions like strpos, explode, array_push etc. With the folllowing code, how do i input ONLY the multiple elements into the end of an array, without creating another & placing that into an existing array?
$test = array();
$test = array ("testing");
$str = 'a,b,c,d';
$parts = explode(',', $str);
array_push ($test, $parts); //another array inserted into $test, which is not what I want
print_r($test);
Use array_merge.
$test = array_merge($test, $parts);
Example: http://3v4l.org/r7vaB

PHP get everything in a string before underscore

I have this code here:
$imagePreFix = substr($fileinfo['basename'], strpos($fileinfo['basename'], "_") +1);
this gets me everything after the underscore, but I am looking to get everything before the underscore, how would I adjust this code to get everything before the underscore?
$fileinfo['basename'] is equal to 'feature_00'
Thanks
You should simple use:
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));
I don't see any reason to use explode and create extra array just to get first element.
You can also use (in PHP 5.3+):
$imagePreFix = strstr($fileinfo['basename'], '_', true);
If you are completely sure that there always be at least one underscore, and you are interested in first one:
$str = $fileinfo['basename'];
$tmp = explode('_', $str);
$res = $tmp[0];
Other way to do this:
$str = "this_is_many_underscores_example";
$matches = array();
preg_match('/^[a-zA-Z0-9]+/', $str, $matches);
print_r($matches[0]); //will produce "this"
(probably regexp pattern will need adjustments, but for purpose of this example it works just fine).
I think the easiest way to do this is to use explode.
$arr = explode('_', $fileinfo['basename']);
echo $arr[0];
This will split the string into an array of substrings. The length of the array depends on how many instances of _ there was. For example
"one_two_three"
Would be broken into an array
["one", "two", "three"]
Here's some documentation
If you want an old-school answer in the type of what you proposed you can still do the following:
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));

How to use explode and get first element in one line in PHP?

$beforeDot = explode(".", $string)[0];
This is what I'm attempting to do, except that it returns syntax error. If there is a workaround for a one liner, please let me know. If this is not possible, please explain.
The function array dereferencing was implemented in PHP 5.4, so if you are using an older version you'll have to do it another way.
Here's a simple way to do it:
$beforeDot = array_shift(explode('.', $string));
You can use list for this:
list($first) = explode(".", "foo.bar");
echo $first; // foo
This also works if you need the second (or third, etc.) element:
list($_, $second) = explode(".", "foo.bar");
echo $second; // bar
But that can get pretty clumsy.
Use current(), to get first position after explode:
$beforeDot = current(explode(".", $string));
Use array_shift() for this purpose :
$beforeDot = array_shift(explode(".", $string));
in php <= 5.3 you need to use
$beforeDot = explode(".", $string);
$beforeDot = $beforeDot[0];
2020 : Google brought me here for something similar.
Pairing 'explode' with 'implode' to populate a variable.
explode -> break the string into an array at the separator
implode -> get a string from that first array element into a variable
$str = "ABC.66778899";
$first = implode(explode('.', $str, -1));
Will give you 'ABC' as a string.
Adjust the limit argument in explode as per your string characteristics.
You can use the limit parameter in the explode function
explode($separator, $str, $limit)
$txt = 'the quick brown fox';
$explode = explode(' ', $txt, -substr_count($txt, ' '));
This will return an array with only one index that has the first word which is "the"
PHP Explode docs
Explanation:
If the limit parameter is negative, all components except the last
-limit are returned.
So to get only the first element despite the number of occurences of the substr you use -substr_count

Put all explode arrays to one string

let's say I have a string called str, I dont know how long is that.
characters in the string are separated by '-' after each 16th character.
Now i called function like $ex = explode('-', $str);.
Now it is in array. I have changed some chracters in array. for example $ex[0][0] = 'a';
Now I want to connect that changed arrays back to variable $str2.
Something like $str2 = $ex[0].ex[1] but I don't know how long is that array.
Do you know how?
IF you didnt understand my explaination, tell me.
Thank you really much.
I think you want implode:
http://php.net/manual/en/function.implode.php
Example:
$str2 = implode('', $ex);
Try:
$str2 = implode('-', $ex);
This will take all of the elements of $ex and connect them into one string with the first parameter between each element. In this case: -.
If you don't want them to be connected by anything, then you can just do:
$str2 = implode($ex);
Use foreach. Foreach allows you to run through the array and automatically stop when the end has been reached.
An example would be:
foreach ($ex as $e) {
$str2 .= $e;
}

Categories