首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在PHP中把字符串切成不同的部分?

在PHP中把字符串切成不同的部分?
EN

Stack Overflow用户
提问于 2014-02-18 23:14:52
回答 6查看 136关注 0票数 0

我是PHP的新手,我需要根据值而不是字符数将字符串分割成特定的部分。

我听说过explode函数和子字符串,但我不知道如何使用它来实现我想要的。

我得到了一个输出字符串:

Name: example Email: e.g@example.com Website: http://examples.com/ Comment: this is where the comment goes, we can't use explode because there's lots of spaces here Another comment: this is another comment Some random info: this is more info...

为了美观起见,我想在单独的行中显示此信息。

有没有办法在一个特定的单词之后但在另一个特定的单词之前返回一个单词?

EN

回答 6

Stack Overflow用户

发布于 2014-02-18 23:42:49

您可以使用正则表达式来实现这一点,前提是给定的字符串始终是正则格式的。

使用preg_split()可能构成了基础:

代码语言:javascript
复制
$arr = preg_split('/(?=[A-Z])/', $str, -1, PREG_SPLIT_NO_EMPTY);

正则表达式使用positive lookahead断言在任何大写字母之前的位置拆分给定的字符串。

如果我们在阵列上执行print_r(),您可以看到以下输出:

代码语言:javascript
复制
Array
(
    [0] => Name: example 
    [1] => Email: e.g@example.com 
    [2] => Website: http://examples.com/ 
    [3] => Comment: this is where the comment goes ... 
    [4] => Another comment: this is another comment 
    [5] => Some random info: this is more info...
)

首先,你是如何获得这个字符串的?如果这是您控制范围内的事情,那么我强烈建议使用JSON或类似的方法来传输数据。它更简单,错误更少--而且你可以确定它是有效的。

票数 3
EN

Stack Overflow用户

发布于 2014-02-18 23:42:50

这是可行的-

代码语言:javascript
复制
$regex = "/[A-Z][^A-Z]*?\:\s.*?(?(?=[A-Z][^A-Z]*?\:)|$)/";
$string = "Name: Example Email: e.g@example.com Website: http://examples.com/ Comment: this is where the comment goes, we can't use explode Because there's Lots of spaces here Another comment: this is another comment Some random info: this is more info";
if(preg_match_all($regex, $string, $matches)){
    var_dump($matches[0]);
}
/*
OUTPUT
array
  0 => string 'Name: Example ' (length=14)
  1 => string 'Email: e.g@example.com ' (length=23)
  2 => string 'Website: http://examples.com/ ' (length=30)
  3 => string 'Comment: this is where the comment goes, we can't use explode Because there's Lots of spaces here ' (length=98)
  4 => string 'Another comment: this is another comment ' (length=41)
  5 => string 'Some random info: this is more info' (length=35)

*/
票数 2
EN

Stack Overflow用户

发布于 2014-02-18 23:18:15

使用像这样的简单字符串操作函数,让你的生活变得简单。

代码语言:javascript
复制
<?php
      $strx='Name: example Email: user@example.com Website: http://example.com/';
      $str=stristr($strx,"Comment :",true);// Take all chars before 'Comments :'
      $str= str_replace(": ",":",str);
      $str = str_replace(" ","\n");          
      echo $str . '\n Comment : '. ; // Its 
      echo stristr($strx,"Comment :"); // Done
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21857863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档