如何将字符串更改为另一种格式?

时间:2016-01-09 04:45:43

标签: php string

所以我有这样的字符串:

1)what is capital of india?a)bangloreb)delhic)Hyderabad2)what is capital of telangana?a)hydb)khammamc)warangal

我想将其更改为:

1)what is capital of India?
A)Bangalore
B)Delhi
C)Hyderabad

2)what is capital of telangana?
A)Hyd
B)khammam
C)waranagal

有人可以给我任何建议或提示我如何做到这一点?

2 个答案:

答案 0 :(得分:0)

<?php
$data ="1)what is capital of india?a)bangloreb)delhic)Hyderabad2)what is capital of telangana?a)hydb)khammamc)warangal";
$data= str_replace("a)"," A)","$data");
$data= str_replace("b)"," B)","$data");
$data= str_replace("c)"," C)","$data");
$data= str_replace("d)"," D)","$data");

echo str_replace("2)"," <br/>2)","$data");

&GT;

运行此代码,这将对您有所帮助。

答案 1 :(得分:0)

使用@Avinash Raj回答,这里是代码片段:

$str = "1)what is capital of india?a)bangloreb)delhic)Hyderabad2)what is capital of telangana?a)hydb)khammamc)warangal";

$str = preg_replace('~(?=\w\))~', '<br/>', $str );
echo $str ;

预期输出为:

<br/>1)what is capital of india?<br/>a)banglore<br/>b)delhi<br/>c)Hyderabad<br/>2)what is capital of telangana?<br/>a)hyd<br/>b)khammam<br/>c)warangal

结果是:


1)什么是印度的首都?a)banglore
b)德里·c)海德拉巴2)什么是特兰甘娜的首都? />一)水合
b)中坎曼
c)中瓦朗加尔

UPDATE:

代码更新为首字母大写。

<?php

$str = "1)what is capital of india?a)bangloreb)delhic)Hyderabad2)what is capital of telangana?a)hydb)khammamc)warangal";

$str = preg_replace('~(?=\w\))~', '|', $str );
$arr = explode('|', $str);

for ($x = 0; $x < count($arr); $x++) {
    $value = $arr[$x];
    $arr[$x] = ucfirst($value);
}

$arr = implode("<br/>", $arr);

print_r($arr);