I have a string with a different variety of strings of different lengths
Example:
/my-big-property/Residential/Sections-for-sale
/my-big-property/Residential/for-sale
I am wanting to only remove /my-big-property/ but because substr does not seem to work what other options do I have?
Can you explain further by substr doesn't work? This seems like an awfully simple problem.
<?php
$a = "/my-big-property/Residential/Sections-for-sale";
$b = substr($a, 17);
echo $b;
If the initial string between the first / and second / is variable, then regex such as this would suffice:
<?php
$a = "/my-big-property/Residential/Sections-for-sale";
preg_match("/\/\S+?\/(.*)/", $a, $matches);
print_r($matches);
This would output:
Array
(
[0] => /my-big-property/Residential/Sections-for-sale
[1] => Residential/Sections-for-sale
)
substr is working fine, you are just not using it properly. It is a function not a procedure.
It does not change the original string but returns a new substring.
Above all the suggested solutions which are correct you can simply use the following:
$string="/my-big-property/Residential/Sections-for-sale";
$string = str_replace("/my-big-property/", "", $string);
<?php
$a = "/my-big-property/Residential/Sections-for-sale";
$temp = explode('/my-big-property/',$a);
$temp_ans = $temp[1];
echo $temp_ans;
?>
There will be two array one will be blank and another will have desired value.
Related
I have a code which I have to explode my text using "*" as a delimiter.
I have a pattern that always the array [0] and [1] will be excluded and the rest of them need to be included inside a variable, but my problem is that I don't know how to catch dynamically the rest of the arrays that I have to put them all together inside of it.
Specially because my text may have more "*" and explode into more parts, but I have to get them all together. Excluding the [0] and [1]
$item= explode("*",$c7);
print_r($item);
//so now that I know which are my [0] and [1] arrays I need to get the rest of them inside of another variable
$variable = ?? //the rest of the $item arrays
$str = 'a*b*c*d*e';
$newStr = implode('*', array_slice(explode('*', $str), 2)); // OUTPUT: c*d*e
explode() is used to chunk the string by a delimiter
implode() is used to build a string again from chunks
array_slice() is used to select a range of the elements
I realise an answer was already accepted, but explode has a third argument for this, and with end you can grab that last, non-split part:
$str = 'a*b*c*d*e';
$res = end(explode("*", $str, 3));
$res gets this value as a result:
c*d*e
I think based off of your question, if I interpreted it correctly something like below will be useful.
USING A LOOP
$str = "adssa*asdASD*AS*DA*SD*ASD*AS*DAS*D";
$parts = explode("*", $str);
$newStr = "";
for ($i = 2; $i < count($parts); ++$i) {
$newStr .= $parts[$i];
}
I need to check if URL contains the term: "cidades".
For example:
http://localhost/site/cidades/sp/sorocaba
So, if positive, then I need to create two or three variables with the remaining content without the " / ", in this case:
$var1 = "sp";
$var2 = "sorocaba";
These variables will be cookies values in the beggining of the page, then, some sections will use as wp-query these values to filter.
This should work for you:
Here I check with preg_match() if the search word is in the url $str between two slashes. If yes I get the substr() from the url after the search word and explode() it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax.
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
output:
sp
sorocaba
Here are two functions that will do it for you:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
And PHP's native explode.
First call afterLast, passing the /cidades/ string (or just cidades if you don't expect the slashes). Then take the result and explode on / to get your resulting array.
It would look like:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
Just note that if you do not include the / marks with the afterLast call, your first element in the explode array will be empty.
I think this solution is better, since the resulting array will support any number of values, not just two.
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'], "_"));
I have a php string of the form :
somename_XXX_someothername_YYY
XXX & YYY = Integers
I want to extract somename and XXX in an array, such that:
array [0] => somename
array [1] => XXX
Following is my approach of achieving it:
$a = array();
$x = 'stack_312_overflow_213';
$a[] = strstr($x, '_', true);
$a[] = strstr(ltrim(strstr($x, '_', false), '_'), '_', true);
I wanted to know if there way any other faster way of doing it as my application will be trimming about 10,000+ strings in this way.
P.S.: I don't know much about speeds, or which php functions are the fastest, so thought of posting it here.
Faster then explode and preg_match:
list($word, $num) = sscanf($x, '%[^_]_%d');
Also you will have $num as integer already.
If you are willing to use explode, limit it with 3 to speed it up, also you will lose time on casting int on $num if you need it:
explode('_', $x, 3);
Just use $arr = explode('_', $str); and the values in the [0] and [1] spot are the first two values you requested
Below are two ways you can get the information from the string.
Which one of the two is faster? I really have no idea, but you can test it.
This result is from the explode:
$result = explode('_', 'somename_XXX_someothername_YYY', 3);
print_r($result);
Using a regular expression:
$matches = array();
preg_match('/^(.*?)_(.*?)_/', 'somename_XXX_someothername_YYY', $matches);
array_shift($matches); //will remove the first match, which is "somename_XXX_"
print_r($matches);
I want to be able to specify an index in a string and remove it.
I have the following:
"Hello World!!"
I want to remove the 4th index (o in Hello). Here would be the end result:
"Hell World!!"
I've tried unset(), but that hasn't worked. I've Googled how to do this and that's what everyone says, but it hasn't worked for me. Maybe I wasn't using it right, idk.
This is a generic way to solve it:
$str = "Hello world";
$i = 4;
echo substr_replace($str, '', $i, 1);
Basically, replace the part of the string before from the index onwards with the part of the string that's adjacent.
See also: substr_replace()
Or, simply:
substr($str, 0, $i) . substr($str, $i + 1)
$str="Hello World";
$str1 = substr($str,0,4);
$str2 = substr($str,5,7);
echo $str1.$str2;
This php specific of working with strings also bugged me for a while. Of course natural solution is to use string functions or use arrays but this is slower than directly working with string index in my opinion. With the following snippet issue is that in memory string is only replaced with empty � and if you have comparison or something else this is not good option. Maybe in future version we will get built in function to remove string indexes directly who knows.
$string = 'abcdefg';
$string[3] = '';
var_dump($string);
echo $string;
$myVar = "Hello World!!";
$myArray = str_split($myVar);
array_splice($myArray, 4, 1);
$myVar = implode("", $myArray);
Personal I like dealing with arrays.
(Sorry about lack of code brackets putting this up via my phone)
I think can create a function and call it like this
function rem_inx ($str, $ind)
{
return substr($str,0,$ind++). substr($str,$ind);
}
//use
echo rem_inx ("Hello World!!", 4);