How find words and abolish (delete) characters aft

2019-08-12 06:18发布

问题:

If I want to check 'php' exist in a string and delete the words after it I could just use:

$string = 'hello world php is a bla bla..';
$string = explode(' php ', $string);
echo $string[0];

But what if I have multiple words instead of just 'php'? For example few song name below has 'feats','feat','ft','ft.'.. that's four of them.

I want to make like 'sia - elastic feat brunos mars' become just 'sia - elastic'.

回答1:

This is the code that you need:

<?php

$string = 'sia - elastic feat brunos mars';

$array = array('feats', 'feat', 'ft', 'ft.');

for($i = 0; $i < count($array); $i++) {
  $out = explode(' ' . $array[$i] . ' ', $string);
  if (count($out) > 1) {
       break;
  }   
}

echo $out[0];

?>


回答2:

you can use

 $string = 'hello world php is a bla bla..';
 $string_before = strstr($string, 'php', true); 

this will check for the first occurrence of the string 'php'.. and remove the rest after that.