In PHP
there exist no special ../
(or any other string) that when concatenated to another string generates any string other than the combine original string concatenated with the new string. Concatenation, regardless of content of strings always results in:
"<String1><String2>" = "<String1>"."<String2>";
Nothing will not ‘erase’ prior tokens in a string or anything like that and is completely harmless.
Caveat!!!! Of course if the string is being used somewhere that interprets it in some specific way where any character or group of characters in the ../
is treated special such as:
- In a string used for regex pattern
- In a string used as a file path (in that case, when it’s evaluated it will do exactly what you’d expect if you’d typed it.
- A string used in a SQL query without properly escaping (as with binding params/values via prepared statements)
- etc…
Now, if you want to remove the word prior to each occurence of ../
starting a word in a sentence, sort-of replicating how the ..
in a path means, go up one level (in effect undoing the step made to the directory in the path prior to it).
Here’s a basic algorithm to start you out (if you are able to change the source code) :
- Use explode with delimiter
" "
on the string. - Create a new array
- Iterate the returned array, if not
../
insert at end of new array - if entry starts with
../
, remove the end element of the 2nd array - insert the the
../somestring
with the../
string replaced with empty string""
on the end of the 2nd array - Once at end of array (all strings processed),
implode()
with delimiter" "
Here’s an example:
<?php
$variable = "../Hi";
$string = "Hello ". $variable . " World"; // Note: I added a space prior to the W
$arr = array();
foreach(explode(" ", $string) as $word) {
if (substr( $word, 0, 3 ) === "../") {
if(!empty($arr)){
array_pop($arr);
}
$arr[] = str_replace("../", "", $word);
} else {
$arr[] = $word;
}
}
echo implode(" ", $arr);
5
solved Is variable’s value back-slashing available in PHP?