Else if it is a string with just the amount of commas you showed us then this will do:
$str = "27328, , File Name Title, , , http://www.domain.com/wp-content/upl...name-title.pdf ";
// use explode to break the parts into an array
$bits = explode(",",$str);
// get rid of some the leading white spaces
$bits = array_map("trim" , $bits);
// access the array elements as needed
echo "<a href='". $bits[5] . "'>" . $bits[2] . "</a>";
Hi Cups, this is a string so thanks for this. Is it possible to modify the function so that if the string is empty (i.e. user doesn’t upload a file) to return the text “Not available”.
The simplest way to write it is with an if conditional check.
// comment out one line or the other to test this
$str = "27328, , File Name Title, , , http://www.domain.com/wp-content/upl...name-title.pdf ";
//$str = "";
if(trim($str) === ""){
echo "Not available";
}else{
$bits = explode(",",$str);
$bits = array_map("trim" , $bits);
echo "<a href='". $bits[5] . "'>" . $bits[2] . "</a>";
}
You may then go on to check whether the string contains commas at all, or put it all into a function, or into a class and make it more robust.
We can go on developing this idea to make it handle more possibilities.
You may want to come up with a solution if for example the url is not actually a url, maybe it is missing the http://… If the File Name Title is missing you may want to inject some default text, or send yourself an alert …
A lot will depend on how many places you can see yourself re-using this code, and the range of possible input strings or values – but maybe this bit of code as it stands is all you need.
1/ Put php code in php tags not code tags on the forum post.
2/ The variable $file in ’ ’ will be $file but in " " will be the value of $file.
3/ Try this: