我有一个来自db:$text=
parameter1=value1
parameter2=value2
otherparemeter=othervalue
我需要一个函数来用新值替换参数,但是如果参数不存在;必须添加到字符串;
示例:updatestring ($text,"parameter1","newvalue"):
结果:
parameter1=newvalue
parameter2=value2
otherparemeter=othervalue
或者:updatestring ($text,"myparameter","myvalue"):
结果:
parameter1=value1
parameter2=value2
otherparemeter=othervalue
myparameter=myvalue
谢谢!
答案 0 :(得分:1)
如果每个参数和值都在自己的行上,这可能会有效
function updatestring($text, $param1, $param2)
{
if( stristr($text, $param1.'=') ) $text = preg_replace("`$param1=.*\n`iU", "$param1=$param2".PHP_EOL, $text);
else $text .= PHP_EOL.$param1.'='.$param2;
return $text;
}
答案 1 :(得分:1)
鉴于您输入的格式parse_ini_string应该可以将数据解析为可以轻松更改和重新格式化的结构。
也许是这样的:
$a =<<<EOF
parameter1=value1
parameter2=value2
otherparemeter=othervalue
EOF;
function replacevalue($text, $k, $v){
$dat = parse_ini_string($text);
$ret = "";
if(isset($dat[$k])){
$dat[$k] = $v;
foreach($dat as $prop=>$val){
$ret.= $prop."=".$val."\n";
}
return $ret;
}
}
echo replacevalue($a, "parameter1", "Hello World");
答案 2 :(得分:0)
谢谢@Orangepill;我纠正了你的功能;现在它正在运作
override func viewDidLoad() {
super.viewDidLoad()
// Sets custom nav bar view so we can add multiple bar buttons
navBar = UINavigationBar(frame: CGRectMake(0, 20, UIScreen.mainScreen().bounds.size.width, 44))
navBar.barTintColor = UIColor.blackColor() // Sets bar to black
navBar.translucent = false
self.view.addSubview(navBar)
navItem = UINavigationItem(title: "\(name)") // Sets title
navBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 25)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
// Set icons
var backIcon = UIImage(named: "backButton")
let backButton = UIBarButtonItem(image: backIcon, style: UIBarButtonItemStyle.Plain, target: self, action: "backButton")
navItem.leftBarButtonItem = backButton
var userQuery = PFQuery(className: "Followers")
userQuery.whereKey("following", equalTo: username)
userQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects {
for object in objects {
if let follower = object["follower"] as? String {
if follower == PFUser.currentUser()!.username! {
var followingIcon = UIImage(named: "followingButton")
let followingButton = UIBarButtonItem(image: followingIcon, style: UIBarButtonItemStyle.Plain, target: self, action: "unfollowUser")
self.navItem.rightBarButtonItem = followingButton
self.navItem.rightBarButtonItem?.tintColor = UIColor.orangeColor()
} else {
var followIcon = UIImage(named: "followButton")
let followButton = UIBarButtonItem(image: followIcon, style: UIBarButtonItemStyle.Plain, target: self, action: "followUser")
self.navItem.rightBarButtonItem = followButton
self.navItem.rightBarButtonItem?.tintColor = UIColor.darkGrayColor()
}
}
}
}
} else {
println(error)
}
})