Viewed   74 times

Wanted to convert

<br/>
<br/>
<br/>
<br/>
<br/>

into

<br/>

 Answers

1

You can do this with a regular expression:

preg_replace("/(<brs*/?>s*)+/", "<br/>", $input);

This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.

Wednesday, November 2, 2022
 
1

The variadiac php5.6+ version: (Offers the added benefits of not breaking on missing values and inserting null where values are missing.)

Code: (Demo)

var_export(array_map(function(){return implode(',',func_get_args());},...$text));

The non-variadic version:

Code: (Demo)

foreach($text as $i=>$v){
    $result[]=implode(',',array_column($text,$i));
}
var_export($result);

Input:

$text = [
    ['001','002','003'],
    ['America','Japan','South Korea'],
    ['Washington DC','Tokyo','Seoul']
];

Output from either method:

array (
  0 => '001,America,Washington DC',
  1 => '002,Japan,Tokyo',
  2 => '003,South Korea,Seoul',
)

Nearly exact duplicate page: Combining array inside multidimensional array with same key

Friday, September 16, 2022
5

HTML is not a regular language and cannot be correctly parsed with a regex. Use a DOM parser instead. Here's a solution using PHP's built-in DOMDocument class:

$string = '<ul id="value" name="Bob" custom-tag="customData">';

$dom = new DOMDocument();
$dom->loadHTML($string);

$result = array();

$ul = $dom->getElementsByTagName('ul')->item(0);
if ($ul->hasAttributes()) {
    foreach ($ul->attributes as $attr) {
        $name = $attr->nodeName;
        $value = $attr->nodeValue;    
        $result[$name] = $value;
    }
}

print_r($result);

Output:

Array
(
    [id] => value
    [name] => Bob
    [custom-tag] => customData
)
Thursday, October 13, 2022
 
2

Use implode:

 $tags = implode(', ', array('tag1','tag2','tag3','tag4'));
Friday, September 23, 2022
 
charno
 
1

Tim's regex probably works, but you may want to consider using the DOM functionality of PHP instead of regex, as it may be more reliable in dealing with minor changes in the markup.

See the loadHTML method

Wednesday, November 16, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :