2010-10-21 7 views
7

J'ai des cordes qui ressemble à ceci:Supprimer les caractères après la chaîne?

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

J'essaie de supprimer tout ce qui suit le deuxième tiret, de sorte que je suis parti avec:

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

Donc, au fond, je J'essaie de trouver un moyen de le couper juste avant "- Nom:". J'ai joué avec substr et preg_replace, mais je n'arrive pas à obtenir les résultats escomptés ... Quelqu'un peut-il m'aider?

+0

Peut-il y avoir un 'John Miller - Doe - Nom:' ? Y aura-t-il toujours 'Name:' ​​à la fin? –

+0

Vous pourriez trouver ['s ($ str) -> beforeLast ('-')'] (https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L399) utile, tel que trouvé dans [cette bibliothèque autonome] (https://github.com/delight-im/PHP-Str). – caw

Répondre

19

En supposant que les chaînes auront toujours ce format, une possibilité est:

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

Référence: substr, strpos

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

Bien que la solution après le mien est beaucoup plus agréable ...

2

Tout juste après le deuxième trait d'union, est-ce correct? Une méthode serait

$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" 

Je pensais juste que je jeter cela là-bas comme une alternative bizarre.

+0

Merci pour le partage mate. J'aime cette façon et ça marche pour moi! –

7

Utilisez preg_replace() avec le motif / - 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"; 
?> 

Sortie:

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

Merci beaucoup, cette réponse pourrait être utilisée pour n'importe quelle chaîne. –

0

Une façon plus propre:

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