user1708538 user1708538 - 1 month ago 9
PHP Question

Converting an array into individual URLs - Currently done via line breaks, can I do it by special characters also?

This is the operational part of my code:

$drivers = explode("\r\n", $value );

$value = '';
foreach ($drivers as $dr){
$value .= '<a href="/driver.php?q='. $dr . '~Driver">'. $dr . '</a><br>';
}


The entry in my database is simply a list.

Item1

Item2

Item3

etc.


The code above converts each one into a URL, which then comes out as "www.myurl.com/driver.php?q=Item1"

However, some of the items in this column are written as:

Item4/Item5

Item 6


Of course this means the generated URL is "www.myurl.com/driver.php?q=Item4/Item5". I would like the / to be seen the same way as a line break so Item4 and Item5 are clickable individually when separated by a /, while retaining the original functionality with the line breaks.

Is this possible?

Answer

If I understood the question well, you want to show a/b links as separate links, with the inner text of a and b, respectively, pointing to the page a/b. If I am right, this should be the solution:

$drivers = explode("\r\n", $value );

$value = '';
foreach ($drivers as $dr){
    $elements = ((strpos($dr, "/") === false) ? array(0 => $dr) : (explode("/", $dr)));
    foreach ($elements as $element) {
        $value .= '<a href="/driver.php?q='. $dr . '~Driver">'. $element . '</a><br>';
    }
}

EDIT:

$drivers = explode("\r\n", $value );

$value = '';
foreach ($drivers as $dr){
    $elements = ((strpos($dr, "/") === false) ? array(0 => $dr) : (explode("/", $dr)));
    $index = 0;
    foreach ($elements as $element) {
        $value .= (($index++ === 0) ? '' : '/') . '<a href="/driver.php?q='. $element . '~Driver">'. $element . '</a>' .'<br>';
    }
}

The above untested code attempts to be closer to the real needs.

EDIT2:

$drivers = explode("\r\n", $value );

$value = '';
foreach ($drivers as $dr){
    $elements = ((strpos($dr, "/") === false) ? array(0 => $dr) : (explode("/", $dr)));
    $index = 0;
    foreach ($elements as $element) {
        $value .= (($index++ === 0) ? '' : '/') . '<a href="/driver.php?q='. $element . '~Driver">'. $element . '</a>';
    }
    $value .= '<br>';
}
Comments