2010-10-21 22 views
7

devo stringhe che assomiglia a questo:Rimuovere i caratteri dopo la stringa?

John Miller-Doe - Name: jdoe 
Jane Smith - Name: jsmith 
Peter Piper - Name: ppiper 
Bob Mackey-O'Donnell - Name: bmackeyodonnell 

Sto cercando di rimuovere tutto ciò dopo il secondo trattino, in modo che mi rimane:

John Miller-Doe 
Jane Smith 
Peter Piper 
Bob Mackey-O'Donnell 

Quindi, in sostanza, ho' Sto cercando di trovare un modo per tagliarlo subito prima "- Nome:". Ho giocato con substr e preg_replace, ma non riesco a ottenere i risultati che spero ... Qualcuno può aiutarti?

+0

Ci può essere un 'John Miller - Doe - Nome:' ? Ci sarà sempre 'Nome:' alla fine? –

+0

Si potrebbe trovare ['s ($ str) -> beforeLast ('-')'] (https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L399) utile, come trovato in [questa libreria standalone] (https://github.com/delight-im/PHP-Str). – caw

risposta

19

Supponendo che le stringhe avranno sempre questo formato, una possibilità è:

$short = substr($str, 0, strpos($str, ' - Name:')); 

Riferimento: substr, strpos

1
$string="Bob Mackey-O'Donnell - Name: bmackeyodonnell"; 
$parts=explode("- Name:",$string); 
$name=$parts[0]; 

Anche se la soluzione dopo la mia è molto più bello ...

2

Tutto dopo giusto prima del secondo trattino, quindi? Un metodo sarebbe

$string="Bob Mackey-O'Donnell - Name: bmackeyodonnel"; 
$remove=strrchr($string,'-'); 
//remove is now "- Name: bmackeyodonnell" 
$string=str_replace(" $remove","",$string); 
//note $remove is in quotes with a space before it, to get the space, too 
//$string is now "Bob Mackey-O'Donnell" 

Ho solo pensato di buttarlo lì come alternativa bizzarra.

+0

Grazie per aver condiviso l'amico. amo così e funziona per me! –

7

Utilizzare preg_replace() con il modello / - Name:.*/:

<?php 
$text = "John Miller-Doe - Name: jdoe 
Jane Smith - Name: jsmith 
Peter Piper - Name: ppiper 
Bob Mackey-O'Donnell - Name: bmackeyodonnell"; 

$result = preg_replace("/ - Name:.*/", "", $text); 
echo "result: {$result}\n"; 
?> 

uscita:

result: John Miller-Doe 
Jane Smith 
Peter Piper 
Bob Mackey-O'Donnell 
+0

Grazie mille, questa risposta potrebbe essere usata per qualsiasi stringa. –

0

un modo più pulito:

$find = 'Name'; 
$fullString = 'aoisdjaoisjdoisjdNameoiasjdoijdsf'; 
$output = strstr($fullString, $find, true) . $find ?: $fullString; 
Problemi correlati