【问题标题】:how can i divide one string, (ex:-$x="hello/welcome" ;)to two variable in php [duplicate]我如何将一个字符串(例如:-$x="hello/welcome" ;)划分为 php 中的两个变量 [重复]
【发布时间】:2015-06-12 04:22:06
【问题描述】:

考虑下面的变量 x。是否有任何方法可以将其分成“斜线”处的两个部分并将它们分配给 php.ini 中的两个变量。两个单词之间应该只有斜线。

<?php
    $x="hello/welcome";
?>

【问题讨论】:

  • 使用explode('/', $x)

标签: php html string variables


【解决方案1】:
<?php
$x="hello/welcome";
$a = explode("/", $x);

// $a[0] = "hello"
// $a[1] = "welcome"

?>

有用吗?

【讨论】:

  • 比你先生。行得通。
【解决方案2】:

你可以同时使用explode和preg_split。试试这个:-

<?php
    $x="hello/welcome";
    $array = explode("/", $x);
    echo "<pre/>";print_r($array);
?>

或者

<?php
    $x="hello/welcome";
    $y = preg_split('^/^',$x);
    print_r($y);
?>

在这两种情况下输出都是:-

Array
(
    [0] => hello
    [1] => welcome
)

【讨论】:

  • 似乎没问题,但恕我直言,没有必要使用正则表达式:)
  • 我只是举了例子。就是这样。:)
  • Regex 在这里不是很好的解决方案。当这是简单的字符串操作问题时,这里不需要额外的正则表达式开销。
猜你喜欢
  • 2021-12-11
  • 1970-01-01
  • 2015-05-29
  • 2019-05-01
  • 1970-01-01
  • 2014-08-30
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多