Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

php - How do i return the remainder of a string?

I have some text in string which i want to split in half but so it breaks after a complete word.

$text = "This is a string of test text";

I used substr() which was great but cut a word in half.

substr($text, 0, 15);

resulted in outputting: "This is a strin"

So I found and tried this approach:

$part1=$text;
if (preg_match('/^.{1,15}/s', $text, $match))
{
  $part1=$match[0];
}

which gave me "This is a"

PERFECT!

...but how do i get "string of test text" in another variable?

question from:https://stackoverflow.com/questions/65600755/how-do-i-return-the-remainder-of-a-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's lazy but as you have the part 1, you can get part 2 like this:

$part1=$text;
if (preg_match('/^.{1,15}/s', $text, $match))
{
  $part1=$match[0];
}
$part2 = str_replace($part1, "", $text);

It removes the part 1 from the string and as a result you'll have part 2

Better solution (but a little bit harder) is to get part 2 index by capturing the offset in preg_match method. It gives you the position of the matching string:

$part1=$text;
if (preg_match('/^.{1,15}/s', $text, $match, PREG_OFFSET_CAPTURE))
{
  $part1 = $match[0][0];
  $part2 = substr($text, $match[0][1] + strlen($part1), strlen($text) - strlen($part1));
}

The second solution might need some fixes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...