phpwordpress

How can get First character of string of any html tag and bind to other tag in php?


How can I achieve the below scenario with php?

Case 1

Input : <h2>Test text <img src="./test.png" /></h2>
Output : <span>T</span><h2>est text <img src="./test.png" /></h2>

Case 2

Input : <p>Test text</h2>
Output : <span>T</span><p>est text</p>

Case 3

Input - <h2><img src="./test.png" /> Test text </h2>
Output - <span>T</span><h2><img src="./test.png" /> est text</h2>

In the input html may be there are so many tags will included. I want any of first block holding the html

I have tried below code

<?php
$firstLetter = strip_tags(get_sub_field('text'));
$firstLetter = $firstLetter[0];
?>
<div class="capLetter"><?php echo $firstLetter; ?></div>
<?php echo substr(get_sub_field('text'), 4); ?>

Solution

  • Previous answer gets the issue if the first element comes the <img /> tag then it will not works. So I tried to hide the first char with css.

    Try below code

    var mystring = document.querySelectorAll(".mystring");
    var letter = document.querySelectorAll(".letter");
    
    for (var i = 0; i < mystring.length; i++) {
        const nameletter = mystring[i].textContent.trim();
        letter[i].innerHTML = nameletter.charAt(0);
    }
    .mystring::first-letter,
    .mystring ::first-letter {
        font-size: 0px;
    }
    <div class="firstLetterCaps">
        <h1 class="letter"></h1>
        <div class="mystring"><img src="./test.png" />
            <h2>Welcome to WordPress. This is your first post. Edit or delete it, then
                start writing</h2>
        </div>
    </div>
    <div class="firstLetterCaps">
        <h1 class="letter"></h1>
        <div class="mystring">This is your first post. Edit or delete it, then start writing!</div>
    </div>
    <div class="firstLetterCaps">
        <h1 class="letter"></h1>
        <div class="mystring">Great <em>communications</em>, great <em>design</em> and great <em>results</em> starts with
            <em>well considered thinking</em>
        </div>
    </div>