用用户输入替换文本文件中的占位符[重复]

问题描述 投票:0回答:1

我有一个来自 Android 应用程序的字符串。我还有一个文件(unknown.txt),其中包含一行“20,30,40,2,5,?”。我想编写一个由 Android 应用程序调用的 PHP 脚本来替换“?”在应用程序中的字符串所在的行中,并在替换“?”后放置新字符串。在另一个文本文件(data.txt)中。我知道如何将字符串从应用程序发送到服务器。我想知道如何执行字符串操作来实现此目的。

<?php
//get string from app
$dev=$_POST["devicename"];

//read unknown.txt and fetch string
$file = 'unknown.txt';
$fh = fopen($file,'r');
$data = fread($fh,filesize($file));
fclose($fh);

//need code to replace "?" from $data with contents of $dev
php string file replace
1个回答
1
投票

来自 str_replace():

PHP 文档

str_replace ( 混合 $search , 混合 $replace , 混合 $subject [, int &$计数] )

对于您的具体用例:

//read unknown.txt and fetch string
$file = 'unknown.txt';
$fh = fopen($file,'r');
$data = fread($fh,filesize($file));
fclose($fh);

// replace "?" from $data with contents of $dev
$data = str_replace('?',$dev,$data);

你也可以使用

preg_replace()
,但这看起来就像在需要手术刀的地方使用斧头。

使用

preg_replace()

$data = preg_replace('#\?#',$dev,$data);

此外,与本机 PHP 函数相比,正则表达式往往要慢一些。但了解您的选择是件好事。

© www.soinside.com 2019 - 2024. All rights reserved.