开发者

How can I copy this string while making these modifications

I'm trying to perform a string manipulation on this string. I have an algorithm in mind, but not sure about the php syntax.

<who    not="p" what="v" />
<cares  i="开发者_如何转开发n"   want="m" />
<target my="t"  what="iwant" />

Between each start and end pair < and />, the string my="t" may or may not exist (in this example it only exists on the third line). If it doesn't exist, I want to copy the whole < /> as is. If it exists, I want to add <something /> after it. So I want this string to look like this

<who    not="p" what="v" />
<cares  i="n"   want="m" />
<target my="t"  what="iwant" /><something />

What complicates the situation is that my="t" seems to not have a standard position, it could be anywhere between < />. Any suggestions how to do this with php? I'm thinking regex


First I think you could use regex, or simply combination of substr & strpos to seperate the <... />

You can use strstr to determine if my="t" appears in a string or not, then perform the approriate action.

Actually, I think that breaking your task into smaller tasks, is more simple and easier to refactor than trying to get all in one shot with a magical regex.


Have a try with:

$l = array('<who    not="p" what="v" />','<cares  i="n"   want="m" />','<target my="t"  what="iwant" />');

foreach ($l as $str) {
  $str = preg_replace('#(<.*?my="t".*? />)#', "$1<something />", $str);
  echo $str,"\n";
}

Output:

<who    not="p" what="v" />
<cares  i="n"   want="m" />
<target my="t"  what="iwant" /><something />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜