如何从字符串中删除单词后的所有文本?

如何从字符串中删除单词后的所有文本?

问题描述:

how can i remove a word and after that from paragraph ?

e.g :

How To Remove all text after this (test ) word from a strings ?

ABC DEF GHEE JUL *test MON ...* 

i want to remove test MON ... from my string

and have just :

ABC DEF GHEE JUL

Thanks

我如何从段落中删除一个单词? p>

例如 : p>

如何从字符串中删除此(测试)字后的所有文本? p>

  ABC DEF GHEE JUL *测试MON ..  。* 
  code>  pre> 
 
 

我想从我的字符串中删除测试MON ... strong> p>

我只是: p>

  ABC DEF GHEE JUL 
  code>  pre> 
 
 

谢谢 p> div>

You can split easy

$string = "ABC DEF GHEE JUL test MON";
$splitted = explode("test", $string);
$result = $splitted[0]; //ABC DEF GHEE JUL

The easiest thing would be to simply substring:

$result = substr($string, 0, strpos($string, 'test'));

You may try something like this:

<?php
    $string = "ABC DEF GHEE JUL test MON ...";
    $clean1 = preg_replace("#(\s[a-z]+?).+$#", "", $string);

    var_dump($clean1);  //<== YIELDS: string 'ABC DEF GHEE JUL' (length=16)

You can create functions and reuse them later, like:

$test1=removeAfterFirst("ABC DEF GHEE JUL test MON ...","test ");
// $test1 is "ABC DEF GHEE JUL "

$test2=removeAfterLast("ABC DEF ABC GHE","ABC");
// $test2 is "ABC DEF "

The functions:

public static function removeAfterFirst($text,$value)
{
    $firstOccurence=strpos($text,$value);
    if($firstOccurence===false)
        return $text;
    return substr($text,0,$firstOccurence);
}

public static function removeAfterLast($text,$value)
{
    $lastOccurence=strrpos($text,$value);
    if($lastOccurence===false)
        return $text;
    return substr($text,0,$lastOccurence);
}