Search code examples
phpsqltrim

how can i strip word from a string in php


i am displaying the top 5 results from a sql query using the following code;

    <?php
    $query = "SELECT location, COUNT(location) AS qty FROM ecmt_memberlist GROUP BY location ORDER BY qty DESC LIMIT 0,5"; 

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result))
{
    echo "<span class='graphValue'>x".$row['qty']."</span> " .      $row['location'] . "<br />";

} ?>

this is displaying my result strings as follows:

  • x46 Moon 20 - Sisters of EVE Academy
  • x34 Moon 7 - Ammatar Fleet Assembly Plant
  • x28 Jita x11 Jita IV - Moon 4 - Caldari Navy Assembly Plant
  • x11 Jita IV - Moon 4
  • x9 Lonetrek III - FUUUFAGOLAS

how can i trim down the $row['location'] to show the words before the first "-" for example;

  • x46 Moon 20
  • x34 Moon 7
  • x28 Jita x11 Jita IV
  • x11 Jita IV
  • x9 Lonetrek III

Solution

  • echo explode('-', $row['location'])[0];
    

    OR

    echo preg_replace('/\-\s.+/i', '', $row['location']);