开发者

How can I add text into a certain area?

If I have a line like this,

<option value="someval">somval</option>

how can I position the cursor after the last quotation of value and put something like abcdef?

So the output would be

<option value="somval" abcdef>somval</option>

with PHP?

I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.

@martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:

$query = $db->query("my query....");
while($row = $db->fetch($query)) {

<select name="thename">
    <option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
    <option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
    <option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
    ... Followed by 100 more, because there are a lot of locations to list.
</select>

How can I post all the options I have into a textbox and have the above c开发者_开发百科ode automatically generated to save a lot of time?


Using your example you would do:

while($row = $db->fetch($query)) {
    printf('<option value="someval"%s>someval</option>',
            ($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}

This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try

while($row = $db->fetch($query)) {
    printf('<option value="%s"%s>%s</option>',
            $row['country-code'],
            ($row['country-code'] === $selection) ? ' selected="selected" ' : '',
            row['country-name']);
}

With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.

Note: The usual disclaimers about securing your output apply


You could capture (value=".+?") and replace it with $0 abcdef.

<?php

  $string = '<option value="someval">someval</option>';
  print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);

?>

Which outputs the following:

<option value="someval" abcdef>someval</option>


With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜